diff --git a/01-greeting/index.js b/01-greeting/index.js index 8f551af..5c0279c 100644 --- a/01-greeting/index.js +++ b/01-greeting/index.js @@ -1,4 +1,4 @@ export function greet(name) { // implementar logica aqui - return ""; + return `Hello ${name}`; } diff --git a/node_modules/.bin/browserslist b/node_modules/.bin/browserslist new file mode 100644 index 0000000..68dd69d --- /dev/null +++ b/node_modules/.bin/browserslist @@ -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/../browserslist/cli.js" "$@" +else + exec node "$basedir/../browserslist/cli.js" "$@" +fi diff --git a/node_modules/.bin/browserslist-lint b/node_modules/.bin/browserslist-lint new file mode 100644 index 0000000..8cde7e3 --- /dev/null +++ b/node_modules/.bin/browserslist-lint @@ -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/../update-browserslist-db/cli.js" "$@" +else + exec node "$basedir/../update-browserslist-db/cli.js" "$@" +fi diff --git a/node_modules/.bin/browserslist-lint.cmd b/node_modules/.bin/browserslist-lint.cmd new file mode 100644 index 0000000..2e14905 --- /dev/null +++ b/node_modules/.bin/browserslist-lint.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%\..\update-browserslist-db\cli.js" %* diff --git a/node_modules/.bin/browserslist-lint.ps1 b/node_modules/.bin/browserslist-lint.ps1 new file mode 100644 index 0000000..7abdf26 --- /dev/null +++ b/node_modules/.bin/browserslist-lint.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/../update-browserslist-db/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../update-browserslist-db/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../update-browserslist-db/cli.js" $args + } else { + & "node$exe" "$basedir/../update-browserslist-db/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/browserslist.cmd b/node_modules/.bin/browserslist.cmd new file mode 100644 index 0000000..f93c251 --- /dev/null +++ b/node_modules/.bin/browserslist.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%\..\browserslist\cli.js" %* diff --git a/node_modules/.bin/browserslist.ps1 b/node_modules/.bin/browserslist.ps1 new file mode 100644 index 0000000..01e10a0 --- /dev/null +++ b/node_modules/.bin/browserslist.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/../browserslist/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../browserslist/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../browserslist/cli.js" $args + } else { + & "node$exe" "$basedir/../browserslist/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/esparse b/node_modules/.bin/esparse new file mode 100644 index 0000000..1cc1c96 --- /dev/null +++ b/node_modules/.bin/esparse @@ -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/../esprima/bin/esparse.js" "$@" +else + exec node "$basedir/../esprima/bin/esparse.js" "$@" +fi diff --git a/node_modules/.bin/esparse.cmd b/node_modules/.bin/esparse.cmd new file mode 100644 index 0000000..2ca6d50 --- /dev/null +++ b/node_modules/.bin/esparse.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%\..\esprima\bin\esparse.js" %* diff --git a/node_modules/.bin/esparse.ps1 b/node_modules/.bin/esparse.ps1 new file mode 100644 index 0000000..f19ed73 --- /dev/null +++ b/node_modules/.bin/esparse.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/../esprima/bin/esparse.js" $args + } else { + & "$basedir/node$exe" "$basedir/../esprima/bin/esparse.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../esprima/bin/esparse.js" $args + } else { + & "node$exe" "$basedir/../esprima/bin/esparse.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/esvalidate b/node_modules/.bin/esvalidate new file mode 100644 index 0000000..91a4c9b --- /dev/null +++ b/node_modules/.bin/esvalidate @@ -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/../esprima/bin/esvalidate.js" "$@" +else + exec node "$basedir/../esprima/bin/esvalidate.js" "$@" +fi diff --git a/node_modules/.bin/esvalidate.cmd b/node_modules/.bin/esvalidate.cmd new file mode 100644 index 0000000..4c41643 --- /dev/null +++ b/node_modules/.bin/esvalidate.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%\..\esprima\bin\esvalidate.js" %* diff --git a/node_modules/.bin/esvalidate.ps1 b/node_modules/.bin/esvalidate.ps1 new file mode 100644 index 0000000..23699d1 --- /dev/null +++ b/node_modules/.bin/esvalidate.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/../esprima/bin/esvalidate.js" $args + } else { + & "$basedir/node$exe" "$basedir/../esprima/bin/esvalidate.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../esprima/bin/esvalidate.js" $args + } else { + & "node$exe" "$basedir/../esprima/bin/esvalidate.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/import-local-fixture b/node_modules/.bin/import-local-fixture new file mode 100644 index 0000000..79e3180 --- /dev/null +++ b/node_modules/.bin/import-local-fixture @@ -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/../import-local/fixtures/cli.js" "$@" +else + exec node "$basedir/../import-local/fixtures/cli.js" "$@" +fi diff --git a/node_modules/.bin/import-local-fixture.cmd b/node_modules/.bin/import-local-fixture.cmd new file mode 100644 index 0000000..5a3f685 --- /dev/null +++ b/node_modules/.bin/import-local-fixture.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%\..\import-local\fixtures\cli.js" %* diff --git a/node_modules/.bin/import-local-fixture.ps1 b/node_modules/.bin/import-local-fixture.ps1 new file mode 100644 index 0000000..01ef784 --- /dev/null +++ b/node_modules/.bin/import-local-fixture.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/../import-local/fixtures/cli.js" $args + } else { + & "$basedir/node$exe" "$basedir/../import-local/fixtures/cli.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../import-local/fixtures/cli.js" $args + } else { + & "node$exe" "$basedir/../import-local/fixtures/cli.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/jest b/node_modules/.bin/jest new file mode 100644 index 0000000..e6376e8 --- /dev/null +++ b/node_modules/.bin/jest @@ -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/../jest/bin/jest.js" "$@" +else + exec node "$basedir/../jest/bin/jest.js" "$@" +fi diff --git a/node_modules/.bin/jest.cmd b/node_modules/.bin/jest.cmd new file mode 100644 index 0000000..67a602a --- /dev/null +++ b/node_modules/.bin/jest.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%\..\jest\bin\jest.js" %* diff --git a/node_modules/.bin/jest.ps1 b/node_modules/.bin/jest.ps1 new file mode 100644 index 0000000..78a2563 --- /dev/null +++ b/node_modules/.bin/jest.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/../jest/bin/jest.js" $args + } else { + & "$basedir/node$exe" "$basedir/../jest/bin/jest.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../jest/bin/jest.js" $args + } else { + & "node$exe" "$basedir/../jest/bin/jest.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/js-yaml b/node_modules/.bin/js-yaml new file mode 100644 index 0000000..ed78a86 --- /dev/null +++ b/node_modules/.bin/js-yaml @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../js-yaml/bin/js-yaml.js" "$@" +else + exec node "$basedir/../js-yaml/bin/js-yaml.js" "$@" +fi diff --git a/node_modules/.bin/js-yaml.cmd b/node_modules/.bin/js-yaml.cmd new file mode 100644 index 0000000..453312b --- /dev/null +++ b/node_modules/.bin/js-yaml.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%\..\js-yaml\bin\js-yaml.js" %* diff --git a/node_modules/.bin/js-yaml.ps1 b/node_modules/.bin/js-yaml.ps1 new file mode 100644 index 0000000..2acfc61 --- /dev/null +++ b/node_modules/.bin/js-yaml.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/../js-yaml/bin/js-yaml.js" $args + } else { + & "$basedir/node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args + } else { + & "node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/jsesc b/node_modules/.bin/jsesc new file mode 100644 index 0000000..e7105da --- /dev/null +++ b/node_modules/.bin/jsesc @@ -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/../jsesc/bin/jsesc" "$@" +else + exec node "$basedir/../jsesc/bin/jsesc" "$@" +fi diff --git a/node_modules/.bin/jsesc.cmd b/node_modules/.bin/jsesc.cmd new file mode 100644 index 0000000..eb41110 --- /dev/null +++ b/node_modules/.bin/jsesc.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%\..\jsesc\bin\jsesc" %* diff --git a/node_modules/.bin/jsesc.ps1 b/node_modules/.bin/jsesc.ps1 new file mode 100644 index 0000000..6007e02 --- /dev/null +++ b/node_modules/.bin/jsesc.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/../jsesc/bin/jsesc" $args + } else { + & "$basedir/node$exe" "$basedir/../jsesc/bin/jsesc" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../jsesc/bin/jsesc" $args + } else { + & "node$exe" "$basedir/../jsesc/bin/jsesc" $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/node-which b/node_modules/.bin/node-which new file mode 100644 index 0000000..aece735 --- /dev/null +++ b/node_modules/.bin/node-which @@ -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/../which/bin/node-which" "$@" +else + exec node "$basedir/../which/bin/node-which" "$@" +fi diff --git a/node_modules/.bin/node-which.cmd b/node_modules/.bin/node-which.cmd new file mode 100644 index 0000000..8738aed --- /dev/null +++ b/node_modules/.bin/node-which.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%\..\which\bin\node-which" %* diff --git a/node_modules/.bin/node-which.ps1 b/node_modules/.bin/node-which.ps1 new file mode 100644 index 0000000..cfb09e8 --- /dev/null +++ b/node_modules/.bin/node-which.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/../which/bin/node-which" $args + } else { + & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../which/bin/node-which" $args + } else { + & "node$exe" "$basedir/../which/bin/node-which" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/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/resolve b/node_modules/.bin/resolve new file mode 100644 index 0000000..757d454 --- /dev/null +++ b/node_modules/.bin/resolve @@ -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/../resolve/bin/resolve" "$@" +else + exec node "$basedir/../resolve/bin/resolve" "$@" +fi diff --git a/node_modules/.bin/resolve.cmd b/node_modules/.bin/resolve.cmd new file mode 100644 index 0000000..1a017c4 --- /dev/null +++ b/node_modules/.bin/resolve.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%\..\resolve\bin\resolve" %* diff --git a/node_modules/.bin/resolve.ps1 b/node_modules/.bin/resolve.ps1 new file mode 100644 index 0000000..f22b2d3 --- /dev/null +++ b/node_modules/.bin/resolve.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/../resolve/bin/resolve" $args + } else { + & "$basedir/node$exe" "$basedir/../resolve/bin/resolve" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../resolve/bin/resolve" $args + } else { + & "node$exe" "$basedir/../resolve/bin/resolve" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 100644 index 0000000..77443e7 --- /dev/null +++ b/node_modules/.bin/semver @@ -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/../semver/bin/semver.js" "$@" +else + exec node "$basedir/../semver/bin/semver.js" "$@" +fi diff --git a/node_modules/.bin/semver.cmd b/node_modules/.bin/semver.cmd new file mode 100644 index 0000000..9913fa9 --- /dev/null +++ b/node_modules/.bin/semver.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%\..\semver\bin\semver.js" %* diff --git a/node_modules/.bin/semver.ps1 b/node_modules/.bin/semver.ps1 new file mode 100644 index 0000000..314717a --- /dev/null +++ b/node_modules/.bin/semver.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/../semver/bin/semver.js" $args + } else { + & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../semver/bin/semver.js" $args + } else { + & "node$exe" "$basedir/../semver/bin/semver.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..469fcc9 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,3101 @@ +{ + "name": "challenge-algorithms", + "version": "1.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@ampproject/remapping": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.2.0.tgz", + "integrity": "sha512-qRmjj8nj9qmLTQXXmaR1cck3UXSRMPrbsLJAasZpF+t3riI71BXed5ebIOYwQntykeZuhjsdweEc9BxH5Jc26w==", + "dependencies": { + "@jridgewell/gen-mapping": "^0.1.0", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.18.6.tgz", + "integrity": "sha512-TDCmlK5eOvH+eH7cdAFlNXeVJqWIQ7gW9tY1GJIpUtFb6CmjVyq2VM3u71bOyR8CRihcCgMUYoDNyLXao3+70Q==", + "dependencies": { + "@babel/highlight": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.19.4", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.19.4.tgz", + "integrity": "sha512-CHIGpJcUQ5lU9KrPHTjBMhVwQG6CQjxfg36fGXl3qk/Gik1WwWachaXFuo0uCWJT/mStOKtcbFJCaVLihC1CMw==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.19.6", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.19.6.tgz", + "integrity": "sha512-D2Ue4KHpc6Ys2+AxpIx1BZ8+UegLLLE2p3KJEuJRKmokHOtl49jQ5ny1773KsGLZs8MQvBidAF6yWUJxRqtKtg==", + "dependencies": { + "@ampproject/remapping": "^2.1.0", + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.19.6", + "@babel/helper-compilation-targets": "^7.19.3", + "@babel/helper-module-transforms": "^7.19.6", + "@babel/helpers": "^7.19.4", + "@babel/parser": "^7.19.6", + "@babel/template": "^7.18.10", + "@babel/traverse": "^7.19.6", + "@babel/types": "^7.19.4", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.1", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.19.6", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.19.6.tgz", + "integrity": "sha512-oHGRUQeoX1QrKeJIKVe0hwjGqNnVYsM5Nep5zo0uE0m42sLH+Fsd2pStJ5sRM1bNyTUUoz0pe2lTeMJrb/taTA==", + "dependencies": { + "@babel/types": "^7.19.4", + "@jridgewell/gen-mapping": "^0.3.2", + "jsesc": "^2.5.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/generator/node_modules/@jridgewell/gen-mapping": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.2.tgz", + "integrity": "sha512-mh65xKQAzI6iBcFzwv28KVWSmCkdRBWoOh+bYQGW3+6OZvbbN3TqMGo5hqYxQniRcH9F2VZIoJCm4pa3BPDK/A==", + "dependencies": { + "@jridgewell/set-array": "^1.0.1", + "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/trace-mapping": "^0.3.9" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.19.3", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.19.3.tgz", + "integrity": "sha512-65ESqLGyGmLvgR0mst5AdW1FkNlj9rQsCKduzEoEPhBCDFGXvz2jW6bXFG6i0/MrV2s7hhXjjb2yAzcPuQlLwg==", + "dependencies": { + "@babel/compat-data": "^7.19.3", + "@babel/helper-validator-option": "^7.18.6", + "browserslist": "^4.21.3", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-environment-visitor": { + "version": "7.18.9", + "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.18.9.tgz", + "integrity": "sha512-3r/aACDJ3fhQ/EVgFy0hpj8oHyHpQc+LPtJoY9SzTThAsStm4Ptegq92vqKoE3vD706ZVFWITnMnxucw+S9Ipg==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-function-name": { + "version": "7.19.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.19.0.tgz", + "integrity": "sha512-WAwHBINyrpqywkUH0nTnNgI5ina5TFn85HKS0pbPDfxFfhyR/aNQEn4hGi1P1JyT//I0t4OgXUlofzWILRvS5w==", + "dependencies": { + "@babel/template": "^7.18.10", + "@babel/types": "^7.19.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-hoist-variables": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.18.6.tgz", + "integrity": "sha512-UlJQPkFqFULIcyW5sbzgbkxn2FKRgwWiRexcuaR8RNJRy8+LLveqPjwZV/bwrLZCN0eUHD/x8D0heK1ozuoo6Q==", + "dependencies": { + "@babel/types": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.18.6.tgz", + "integrity": "sha512-0NFvs3VkuSYbFi1x2Vd6tKrywq+z/cLeYC/RJNFrIX/30Bf5aiGYbtvGXolEktzJH8o5E5KJ3tT+nkxuuZFVlA==", + "dependencies": { + "@babel/types": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.19.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.19.6.tgz", + "integrity": "sha512-fCmcfQo/KYr/VXXDIyd3CBGZ6AFhPFy1TfSEJ+PilGVlQT6jcbqtHAM4C1EciRqMza7/TpOUZliuSH+U6HAhJw==", + "dependencies": { + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-module-imports": "^7.18.6", + "@babel/helper-simple-access": "^7.19.4", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/helper-validator-identifier": "^7.19.1", + "@babel/template": "^7.18.10", + "@babel/traverse": "^7.19.6", + "@babel/types": "^7.19.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.19.0", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.19.0.tgz", + "integrity": "sha512-40Ryx7I8mT+0gaNxm8JGTZFUITNqdLAgdg0hXzeVZxVD6nFsdhQvip6v8dqkRHzsz1VFpFAaOCHNn0vKBL7Czw==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-simple-access": { + "version": "7.19.4", + "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.19.4.tgz", + "integrity": "sha512-f9Xq6WqBFqaDfbCzn2w85hwklswz5qsKlh7f08w4Y9yhJHpnNC0QemtSkK5YyOY8kPGvyiwdzZksGUhnGdaUIg==", + "dependencies": { + "@babel/types": "^7.19.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-split-export-declaration": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.18.6.tgz", + "integrity": "sha512-bde1etTx6ZyTmobl9LLMMQsaizFVZrquTEHOqKeQESMKo4PlObf+8+JA25ZsIpZhT/WEd39+vOdLXAFG/nELpA==", + "dependencies": { + "@babel/types": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.19.4", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.19.4.tgz", + "integrity": "sha512-nHtDoQcuqFmwYNYPz3Rah5ph2p8PFeFCsZk9A/48dPc/rGocJ5J3hAAZ7pb76VWX3fZKu+uEr/FhH5jLx7umrw==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.19.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz", + "integrity": "sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.18.6.tgz", + "integrity": "sha512-XO7gESt5ouv/LRJdrVjkShckw6STTaB7l9BrpBaAHDeF5YZT+01PCwmR0SJHnkW6i8OwW/EVWRShfi4j2x+KQw==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.19.4", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.19.4.tgz", + "integrity": "sha512-G+z3aOx2nfDHwX/kyVii5fJq+bgscg89/dJNWpYeKeBv3v9xX8EIabmx1k6u9LS04H7nROFVRVK+e3k0VHp+sw==", + "dependencies": { + "@babel/template": "^7.18.10", + "@babel/traverse": "^7.19.4", + "@babel/types": "^7.19.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.18.6.tgz", + "integrity": "sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g==", + "dependencies": { + "@babel/helper-validator-identifier": "^7.18.6", + "chalk": "^2.0.0", + "js-tokens": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/highlight/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" + }, + "node_modules/@babel/highlight/node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/highlight/node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/parser": { + "version": "7.19.6", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.19.6.tgz", + "integrity": "sha512-h1IUp81s2JYJ3mRkdxJgs4UvmSsRvDrx5ICSJbPvtWYv5i1nTBGcBpnog+89rAFMwvvru6E5NUHdBe01UeSzYA==", + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-syntax-async-generators": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", + "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-bigint": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", + "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-class-properties": { + "version": "7.12.13", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", + "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.12.13" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-meta": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", + "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-json-strings": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", + "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-jsx": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.18.6.tgz", + "integrity": "sha512-6mmljtAedFGTWu2p/8WIORGwy+61PLgOMPOdazc7YoJ9ZCWUyFy3A6CpPkRKLKD1ToAesxX8KGEViAiLo9N+7Q==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-logical-assignment-operators": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", + "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", + "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-numeric-separator": { + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", + "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.10.4" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-object-rest-spread": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", + "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-catch-binding": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", + "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-optional-chaining": { + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", + "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.8.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-top-level-await": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", + "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-typescript": { + "version": "7.18.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.18.6.tgz", + "integrity": "sha512-mAWAuq4rvOepWCBid55JuRNvpTNf2UGVgoz4JV0fXEKolsVZDzsa4NqCef758WZJj/GDu0gVGItjKFiClTAmZA==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.18.6" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.18.10", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.18.10.tgz", + "integrity": "sha512-TI+rCtooWHr3QJ27kJxfjutghu44DLnasDMwpDqCXVTal9RLp3RSYNh4NdBrRP2cQAoG9A8juOQl6P6oZG4JxA==", + "dependencies": { + "@babel/code-frame": "^7.18.6", + "@babel/parser": "^7.18.10", + "@babel/types": "^7.18.10" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.19.6", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.19.6.tgz", + "integrity": "sha512-6l5HrUCzFM04mfbG09AagtYyR2P0B71B1wN7PfSPiksDPz2k5H9CBC1tcZpz2M8OxbKTPccByoOJ22rUKbpmQQ==", + "dependencies": { + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.19.6", + "@babel/helper-environment-visitor": "^7.18.9", + "@babel/helper-function-name": "^7.19.0", + "@babel/helper-hoist-variables": "^7.18.6", + "@babel/helper-split-export-declaration": "^7.18.6", + "@babel/parser": "^7.19.6", + "@babel/types": "^7.19.4", + "debug": "^4.1.0", + "globals": "^11.1.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.19.4", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.19.4.tgz", + "integrity": "sha512-M5LK7nAeS6+9j7hAq+b3fQs+pNfUtTGq+yFFfHnauFA8zQtLRfmuipmsKDKKLuyG+wC8ABW43A153YNawNTEtw==", + "dependencies": { + "@babel/helper-string-parser": "^7.19.4", + "@babel/helper-validator-identifier": "^7.19.1", + "to-fast-properties": "^2.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@bcoe/v8-coverage": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", + "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==" + }, + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@istanbuljs/schema": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.3.tgz", + "integrity": "sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/console": { + "version": "29.2.1", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.2.1.tgz", + "integrity": "sha512-MF8Adcw+WPLZGBiNxn76DOuczG3BhODTcMlDCA4+cFi41OkaY/lyI0XUUhi73F88Y+7IHoGmD80pN5CtxQUdSw==", + "dependencies": { + "@jest/types": "^29.2.1", + "@types/node": "*", + "chalk": "^4.0.0", + "jest-message-util": "^29.2.1", + "jest-util": "^29.2.1", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/core": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.2.2.tgz", + "integrity": "sha512-susVl8o2KYLcZhhkvSB+b7xX575CX3TmSvxfeDjpRko7KmT89rHkXj6XkDkNpSeFMBzIENw5qIchO9HC9Sem+A==", + "dependencies": { + "@jest/console": "^29.2.1", + "@jest/reporters": "^29.2.2", + "@jest/test-result": "^29.2.1", + "@jest/transform": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.2.0", + "jest-config": "^29.2.2", + "jest-haste-map": "^29.2.1", + "jest-message-util": "^29.2.1", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.2.2", + "jest-resolve-dependencies": "^29.2.2", + "jest-runner": "^29.2.2", + "jest-runtime": "^29.2.2", + "jest-snapshot": "^29.2.2", + "jest-util": "^29.2.1", + "jest-validate": "^29.2.2", + "jest-watcher": "^29.2.2", + "micromatch": "^4.0.4", + "pretty-format": "^29.2.1", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/environment": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.2.2.tgz", + "integrity": "sha512-OWn+Vhu0I1yxuGBJEFFekMYc8aGBGrY4rt47SOh/IFaI+D7ZHCk7pKRiSoZ2/Ml7b0Ony3ydmEHRx/tEOC7H1A==", + "dependencies": { + "@jest/fake-timers": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/node": "*", + "jest-mock": "^29.2.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.2.2.tgz", + "integrity": "sha512-zwblIZnrIVt8z/SiEeJ7Q9wKKuB+/GS4yZe9zw7gMqfGf4C5hBLGrVyxu1SzDbVSqyMSlprKl3WL1r80cBNkgg==", + "dependencies": { + "expect": "^29.2.2", + "jest-snapshot": "^29.2.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/expect-utils": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.2.2.tgz", + "integrity": "sha512-vwnVmrVhTmGgQzyvcpze08br91OL61t9O0lJMDyb6Y/D8EKQ9V7rGUb/p7PDt0GPzK0zFYqXWFo4EO2legXmkg==", + "dependencies": { + "jest-get-type": "^29.2.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/fake-timers": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.2.2.tgz", + "integrity": "sha512-nqaW3y2aSyZDl7zQ7t1XogsxeavNpH6kkdq+EpXncIDvAkjvFD7hmhcIs1nWloengEWUoWqkqSA6MSbf9w6DgA==", + "dependencies": { + "@jest/types": "^29.2.1", + "@sinonjs/fake-timers": "^9.1.2", + "@types/node": "*", + "jest-message-util": "^29.2.1", + "jest-mock": "^29.2.2", + "jest-util": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/globals": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.2.2.tgz", + "integrity": "sha512-/nt+5YMh65kYcfBhj38B3Hm0Trk4IsuMXNDGKE/swp36yydBWfz3OXkLqkSvoAtPW8IJMSJDFCbTM2oj5SNprw==", + "dependencies": { + "@jest/environment": "^29.2.2", + "@jest/expect": "^29.2.2", + "@jest/types": "^29.2.1", + "jest-mock": "^29.2.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/reporters": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.2.2.tgz", + "integrity": "sha512-AzjL2rl2zJC0njIzcooBvjA4sJjvdoq98sDuuNs4aNugtLPSQ+91nysGKRF0uY1to5k0MdGMdOBggUsPqvBcpA==", + "dependencies": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.2.1", + "@jest/test-result": "^29.2.1", + "@jest/transform": "^29.2.2", + "@jest/types": "^29.2.1", + "@jridgewell/trace-mapping": "^0.3.15", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^5.1.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.2.1", + "jest-util": "^29.2.1", + "jest-worker": "^29.2.1", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/@jest/schemas": { + "version": "29.0.0", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.0.0.tgz", + "integrity": "sha512-3Ab5HgYIIAnS0HjqJHQYZS+zXc4tUmTmBH3z83ajI6afXp8X3ZtdLX+nXx+I7LNkJD7uN9LAVhgnjDgZa2z0kA==", + "dependencies": { + "@sinclair/typebox": "^0.24.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/source-map": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.2.0.tgz", + "integrity": "sha512-1NX9/7zzI0nqa6+kgpSdKPK+WU1p+SJk3TloWZf5MzPbxri9UEeXX5bWZAPCzbQcyuAzubcdUHA7hcNznmRqWQ==", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.15", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-result": { + "version": "29.2.1", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.2.1.tgz", + "integrity": "sha512-lS4+H+VkhbX6z64tZP7PAUwPqhwj3kbuEHcaLuaBuB+riyaX7oa1txe0tXgrFj5hRWvZKvqO7LZDlNWeJ7VTPA==", + "dependencies": { + "@jest/console": "^29.2.1", + "@jest/types": "^29.2.1", + "@types/istanbul-lib-coverage": "^2.0.0", + "collect-v8-coverage": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/test-sequencer": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.2.2.tgz", + "integrity": "sha512-Cuc1znc1pl4v9REgmmLf0jBd3Y65UXJpioGYtMr/JNpQEIGEzkmHhy6W6DLbSsXeUA13TDzymPv0ZGZ9jH3eIw==", + "dependencies": { + "@jest/test-result": "^29.2.1", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.2.1", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/transform": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.2.2.tgz", + "integrity": "sha512-aPe6rrletyuEIt2axxgdtxljmzH8O/nrov4byy6pDw9S8inIrTV+2PnjyP/oFHMSynzGxJ2s6OHowBNMXp/Jzg==", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/types": "^29.2.1", + "@jridgewell/trace-mapping": "^0.3.15", + "babel-plugin-istanbul": "^6.1.1", + "chalk": "^4.0.0", + "convert-source-map": "^1.4.0", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.2.1", + "jest-regex-util": "^29.2.0", + "jest-util": "^29.2.1", + "micromatch": "^4.0.4", + "pirates": "^4.0.4", + "slash": "^3.0.0", + "write-file-atomic": "^4.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jest/types": { + "version": "29.2.1", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.2.1.tgz", + "integrity": "sha512-O/QNDQODLnINEPAI0cl9U6zUIDXEWXt6IC1o2N2QENuos7hlGUIthlKyV4p6ki3TvXFX071blj8HUhgLGquPjw==", + "dependencies": { + "@jest/schemas": "^29.0.0", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.1.1.tgz", + "integrity": "sha512-sQXCasFk+U8lWYEe66WxRDOE9PjVz4vSM51fTu3Hw+ClTpUSQb718772vH3pyS5pShp6lvQM7SxgIDXXXmOX7w==", + "dependencies": { + "@jridgewell/set-array": "^1.0.0", + "@jridgewell/sourcemap-codec": "^1.4.10" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.0.tgz", + "integrity": "sha512-F2msla3tad+Mfht5cJq7LSXcdudKTWCVYUgw6pLFOOHSTtZlj6SWNYAp+AhuqLmWdBO2X5hPrLcu8cVP8fy28w==", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/set-array": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", + "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.14", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.14.tgz", + "integrity": "sha512-XPSJHWmi394fuUuzDnGz1wiKqWfo1yXecHQMRf2l6hztTO+nPru658AyDngaBe7isIxEkRsPR3FZh+s7iVa4Uw==" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.17", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.17.tgz", + "integrity": "sha512-MCNzAp77qzKca9+W/+I0+sEpaUnZoeasnghNeVc41VZCEKaCH73Vq3BZZ/SzWIgrqE4H4ceI+p+b6C0mHf9T4g==", + "dependencies": { + "@jridgewell/resolve-uri": "3.1.0", + "@jridgewell/sourcemap-codec": "1.4.14" + } + }, + "node_modules/@sinclair/typebox": { + "version": "0.24.51", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.24.51.tgz", + "integrity": "sha512-1P1OROm/rdubP5aFDSZQILU0vrLCJ4fvHt6EoqHEM+2D/G5MK3bIaymUKLit8Js9gbns5UyJnkP/TZROLw4tUA==" + }, + "node_modules/@sinonjs/commons": { + "version": "1.8.3", + "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-1.8.3.tgz", + "integrity": "sha512-xkNcLAn/wZaX14RPlwizcKicDk9G3F8m2nU3L7Ukm5zBgTwiT0wsoFAHx9Jq56fJA1z/7uKGtCRu16sOUCLIHQ==", + "dependencies": { + "type-detect": "4.0.8" + } + }, + "node_modules/@sinonjs/fake-timers": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-9.1.2.tgz", + "integrity": "sha512-BPS4ynJW/o92PUR4wgriz2Ud5gpST5vz6GQfMixEDK0Z8ZCUv2M7SkBLykH56T++Xs+8ln9zTGbOvNGIe02/jw==", + "dependencies": { + "@sinonjs/commons": "^1.7.0" + } + }, + "node_modules/@types/babel__core": { + "version": "7.1.19", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.1.19.tgz", + "integrity": "sha512-WEOTgRsbYkvA/KCsDwVEGkd7WAr1e3g31VHQ8zy5gul/V1qKullU/BU5I68X5v7V3GnB9eotmom4v5a5gjxorw==", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.6.4", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.4.tgz", + "integrity": "sha512-tFkciB9j2K755yrTALxD44McOrk+gfpIpvC3sxHjRawj6PfnQxrse4Clq5y/Rq+G3mrBurMax/lG8Qn2t9mSsg==", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.1", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.1.tgz", + "integrity": "sha512-azBFKemX6kMg5Io+/rdGT0dkGreboUVR0Cdm3fz9QJWpaQGJRQXl7C+6hOTCZcMll7KFyEQpgbYI2lHdsS4U7g==", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.18.2.tgz", + "integrity": "sha512-FcFaxOr2V5KZCviw1TnutEMVUVsGt4D2hP1TAfXZAMKuHYW3xQhe3jTxNPWutgCJ3/X1c5yX8ZoGVEItxKbwBg==", + "dependencies": { + "@babel/types": "^7.3.0" + } + }, + "node_modules/@types/graceful-fs": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.5.tgz", + "integrity": "sha512-anKkLmZZ+xm4p8JWBf4hElkM4XR+EZeA2M9BAkkTldmcyDY4mbdIJnRghDJH3Ov5ooY7/UAoENtmdMSkaAd7Cw==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/istanbul-lib-coverage": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz", + "integrity": "sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==" + }, + "node_modules/@types/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-plGgXAPfVKFoYfa9NpYDAkseG+g6Jr294RqeqcqDixSbU34MZVJRi/P+7Y8GDpzkEwLaGZZOpKIEmeVZNtKsrg==", + "dependencies": { + "@types/istanbul-lib-coverage": "*" + } + }, + "node_modules/@types/istanbul-reports": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.1.tgz", + "integrity": "sha512-c3mAZEuK0lvBp8tmuL74XRKn1+y2dcwOUpH7x4WrF6gk1GIgiluDRgMYQtw2OFcBvAJWlt6ASU3tSqxp0Uu0Aw==", + "dependencies": { + "@types/istanbul-lib-report": "*" + } + }, + "node_modules/@types/node": { + "version": "18.11.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.7.tgz", + "integrity": "sha512-LhFTglglr63mNXUSRYD8A+ZAIu5sFqNJ4Y2fPuY7UlrySJH87rRRlhtVmMHplmfk5WkoJGmDjE9oiTfyX94CpQ==" + }, + "node_modules/@types/prettier": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/@types/prettier/-/prettier-2.7.1.tgz", + "integrity": "sha512-ri0UmynRRvZiiUJdiz38MmIblKK+oH30MztdBVR95dv/Ubw6neWSb8u1XpRb72L4qsZOhz+L+z9JD40SJmfWow==" + }, + "node_modules/@types/stack-utils": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.1.tgz", + "integrity": "sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==" + }, + "node_modules/@types/yargs": { + "version": "17.0.13", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.13.tgz", + "integrity": "sha512-9sWaruZk2JGxIQU+IhI1fhPYRcQ0UuTNuKuCW9bR5fp7qi2Llf7WDzNa17Cy7TKnh3cdxDOiyTu6gaLS0eDatg==", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.0", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.0.tgz", + "integrity": "sha512-iO9ZQHkZxHn4mSakYV0vFHAVDyEOIJQrV2uZ06HxEPcx+mt8swXoZHIbaaJ2crJYFfErySgktuTZ3BeLz+XmFA==" + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", + "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dependencies": { + "sprintf-js": "~1.0.2" + } + }, + "node_modules/babel-jest": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.2.2.tgz", + "integrity": "sha512-kkq2QSDIuvpgfoac3WZ1OOcHsQQDU5xYk2Ql7tLdJ8BVAYbefEXal+NfS45Y5LVZA7cxC8KYcQMObpCt1J025w==", + "dependencies": { + "@jest/transform": "^29.2.2", + "@types/babel__core": "^7.1.14", + "babel-plugin-istanbul": "^6.1.1", + "babel-preset-jest": "^29.2.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.8.0" + } + }, + "node_modules/babel-plugin-istanbul": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", + "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", + "dependencies": { + "@babel/helper-plugin-utils": "^7.0.0", + "@istanbuljs/load-nyc-config": "^1.0.0", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-instrument": "^5.0.4", + "test-exclude": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/babel-plugin-jest-hoist": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.2.0.tgz", + "integrity": "sha512-TnspP2WNiR3GLfCsUNHqeXw0RoQ2f9U5hQ5L3XFpwuO8htQmSrhh8qsB6vi5Yi8+kuynN1yjDjQsPfkebmB6ZA==", + "dependencies": { + "@babel/template": "^7.3.3", + "@babel/types": "^7.3.3", + "@types/babel__core": "^7.1.14", + "@types/babel__traverse": "^7.0.6" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/babel-preset-current-node-syntax": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", + "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", + "dependencies": { + "@babel/plugin-syntax-async-generators": "^7.8.4", + "@babel/plugin-syntax-bigint": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.8.3", + "@babel/plugin-syntax-import-meta": "^7.8.3", + "@babel/plugin-syntax-json-strings": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", + "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.8.3", + "@babel/plugin-syntax-object-rest-spread": "^7.8.3", + "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", + "@babel/plugin-syntax-optional-chaining": "^7.8.3", + "@babel/plugin-syntax-top-level-await": "^7.8.3" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/babel-preset-jest": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.2.0.tgz", + "integrity": "sha512-z9JmMJppMxNv8N7fNRHvhMg9cvIkMxQBXgFkane3yKVEvEOP+kB50lk8DFRvF9PGqbyXxlmebKWhuDORO8RgdA==", + "dependencies": { + "babel-plugin-jest-hoist": "^29.2.0", + "babel-preset-current-node-syntax": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.21.4", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.21.4.tgz", + "integrity": "sha512-CBHJJdDmgjl3daYjN5Cp5kbTf1mUhZoS+beLklHIvkOWscs83YAhLlF3Wsh/lciQYAcbBJgTOD44VtG31ZM4Hw==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + } + ], + "dependencies": { + "caniuse-lite": "^1.0.30001400", + "electron-to-chromium": "^1.4.251", + "node-releases": "^2.0.6", + "update-browserslist-db": "^1.0.9" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/bser": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", + "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", + "dependencies": { + "node-int64": "^0.4.0" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==" + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001425", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001425.tgz", + "integrity": "sha512-/pzFv0OmNG6W0ym80P3NtapU0QEiDS3VuYAZMGoLLqiC7f6FJFe1MjpQDREGApeenD9wloeytmVDj+JLXPC6qw==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + } + ] + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/char-regex": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", + "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", + "engines": { + "node": ">=10" + } + }, + "node_modules/ci-info": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.5.0.tgz", + "integrity": "sha512-yH4RezKOGlOhxkmhbeNuC4eYZKAUsEaGtBuBzDDP1eFUKiccDWzBABxBfOx31IDwDIXMTxWuwAxUGModvkbuVw==" + }, + "node_modules/cjs-module-lexer": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.2.tgz", + "integrity": "sha512-cOU9usZw8/dXIXKtwa8pM0OTJQuJkxMN6w30csNRUerHfeQ5R6U3kkU/FtJeIf3M202OHfY2U8ccInBG7/xogA==" + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } + }, + "node_modules/collect-v8-coverage": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.1.tgz", + "integrity": "sha512-iBPtljfCNcTKNAto0KEtDfZ3qzjJvqE3aTGZsbhjSBlorqpXJlaWWtPO35D+ZImoC3KWejX64o+yPGxhWSTzfg==" + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" + }, + "node_modules/convert-source-map": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.9.0.tgz", + "integrity": "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A==" + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/dedent": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-0.7.0.tgz", + "integrity": "sha512-Q6fKUPqnAHAyhiUgFU7BUzLiv0kd8saH9al7tnu5Q/okj6dnupxyTgFIBjVzJATdfIAm9NAsvXNzjaKa+bxVyA==" + }, + "node_modules/deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/detect-newline": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", + "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/diff-sequences": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.2.0.tgz", + "integrity": "sha512-413SY5JpYeSBZxmenGEmCVQ8mCgtFJF0w9PROdaS6z987XC2Pd2GOKqOITLtMftmyFZqgtCOb/QA7/Z3ZXfzIw==", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.4.284", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.284.tgz", + "integrity": "sha512-M8WEXFuKXMYMVr45fo8mq0wUrrJHheiKZf6BArTKk9ZBYCKJEOU5H8cdWgDT+qCVZf7Na4lVUaZsA+h6uA9+PA==" + }, + "node_modules/emittery": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", + "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sindresorhus/emittery?sponsor=1" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "engines": { + "node": ">=8" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", + "dependencies": { + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sindresorhus/execa?sponsor=1" + } + }, + "node_modules/exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/expect": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/expect/-/expect-29.2.2.tgz", + "integrity": "sha512-hE09QerxZ5wXiOhqkXy5d2G9ar+EqOyifnCXCpMNu+vZ6DG9TJ6CO2c2kPDSLqERTTWrO7OZj8EkYHQqSd78Yw==", + "dependencies": { + "@jest/expect-utils": "^29.2.2", + "jest-get-type": "^29.2.0", + "jest-matcher-utils": "^29.2.2", + "jest-message-util": "^29.2.1", + "jest-util": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" + }, + "node_modules/fb-watchman": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", + "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", + "dependencies": { + "bser": "2.1.1" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/globals": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", + "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", + "engines": { + "node": ">=4" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==" + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==" + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "engines": { + "node": ">=10.17.0" + } + }, + "node_modules/import-local": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", + "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", + "dependencies": { + "pkg-dir": "^4.2.0", + "resolve-cwd": "^3.0.0" + }, + "bin": { + "import-local-fixture": "fixtures/cli.js" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==" + }, + "node_modules/is-core-module": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.11.0.tgz", + "integrity": "sha512-RRjxlvLDkD1YJwDbroBHMb+cukurkDWNyHx7D3oNB5x9rb5ogcksMC5wHCadcXoo67gVr/+3GFySh3134zi6rw==", + "dependencies": { + "has": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", + "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" + }, + "node_modules/istanbul-lib-coverage": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.0.tgz", + "integrity": "sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==", + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-instrument": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", + "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", + "dependencies": { + "@babel/core": "^7.12.3", + "@babel/parser": "^7.14.7", + "@istanbuljs/schema": "^0.1.2", + "istanbul-lib-coverage": "^3.2.0", + "semver": "^6.3.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-report": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.0.tgz", + "integrity": "sha512-wcdi+uAKzfiGT2abPpKZ0hSU1rGQjUQnLvtY5MpQ7QCTahD3VODhcu4wcfY1YtkGaDD5yuydOLINXsfbus9ROw==", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^3.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", + "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "dependencies": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0", + "source-map": "^0.6.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.5.tgz", + "integrity": "sha512-nUsEMa9pBt/NOHqbcbeJEgqIlY/K7rVWUX6Lql2orY5e9roQOthbR3vtY4zzf2orPELg80fnxxk9zUyPlgwD1w==", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/jest": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest/-/jest-29.2.2.tgz", + "integrity": "sha512-r+0zCN9kUqoON6IjDdjbrsWobXM/09Nd45kIPRD8kloaRh1z5ZCMdVsgLXGxmlL7UpAJsvCYOQNO+NjvG/gqiQ==", + "dependencies": { + "@jest/core": "^29.2.2", + "@jest/types": "^29.2.1", + "import-local": "^3.0.2", + "jest-cli": "^29.2.2" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-changed-files": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.2.0.tgz", + "integrity": "sha512-qPVmLLyBmvF5HJrY7krDisx6Voi8DmlV3GZYX0aFNbaQsZeoz1hfxcCMbqDGuQCxU1dJy9eYc2xscE8QrCCYaA==", + "dependencies": { + "execa": "^5.0.0", + "p-limit": "^3.1.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-circus": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.2.2.tgz", + "integrity": "sha512-upSdWxx+Mh4DV7oueuZndJ1NVdgtTsqM4YgywHEx05UMH5nxxA2Qu9T9T9XVuR021XxqSoaKvSmmpAbjwwwxMw==", + "dependencies": { + "@jest/environment": "^29.2.2", + "@jest/expect": "^29.2.2", + "@jest/test-result": "^29.2.1", + "@jest/types": "^29.2.1", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^0.7.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.2.1", + "jest-matcher-utils": "^29.2.2", + "jest-message-util": "^29.2.1", + "jest-runtime": "^29.2.2", + "jest-snapshot": "^29.2.2", + "jest-util": "^29.2.1", + "p-limit": "^3.1.0", + "pretty-format": "^29.2.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-cli": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.2.2.tgz", + "integrity": "sha512-R45ygnnb2CQOfd8rTPFR+/fls0d+1zXS6JPYTBBrnLPrhr58SSuPTiA5Tplv8/PXpz4zXR/AYNxmwIj6J6nrvg==", + "dependencies": { + "@jest/core": "^29.2.2", + "@jest/test-result": "^29.2.1", + "@jest/types": "^29.2.1", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "import-local": "^3.0.2", + "jest-config": "^29.2.2", + "jest-util": "^29.2.1", + "jest-validate": "^29.2.2", + "prompts": "^2.0.1", + "yargs": "^17.3.1" + }, + "bin": { + "jest": "bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + } + }, + "node_modules/jest-config": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.2.2.tgz", + "integrity": "sha512-Q0JX54a5g1lP63keRfKR8EuC7n7wwny2HoTRDb8cx78IwQOiaYUVZAdjViY3WcTxpR02rPUpvNVmZ1fkIlZPcw==", + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.2.2", + "@jest/types": "^29.2.1", + "babel-jest": "^29.2.2", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.2.2", + "jest-environment-node": "^29.2.2", + "jest-get-type": "^29.2.0", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.2.2", + "jest-runner": "^29.2.2", + "jest-util": "^29.2.1", + "jest-validate": "^29.2.2", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.2.1", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "@types/node": "*", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "ts-node": { + "optional": true + } + } + }, + "node_modules/jest-diff": { + "version": "29.2.1", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.2.1.tgz", + "integrity": "sha512-gfh/SMNlQmP3MOUgdzxPOd4XETDJifADpT937fN1iUGz+9DgOu2eUPHH25JDkLVcLwwqxv3GzVyK4VBUr9fjfA==", + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.2.0", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-docblock": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.2.0.tgz", + "integrity": "sha512-bkxUsxTgWQGbXV5IENmfiIuqZhJcyvF7tU4zJ/7ioTutdz4ToB5Yx6JOFBpgI+TphRY4lhOyCWGNH/QFQh5T6A==", + "dependencies": { + "detect-newline": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-each": { + "version": "29.2.1", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.2.1.tgz", + "integrity": "sha512-sGP86H/CpWHMyK3qGIGFCgP6mt+o5tu9qG4+tobl0LNdgny0aitLXs9/EBacLy3Bwqy+v4uXClqJgASJWcruYw==", + "dependencies": { + "@jest/types": "^29.2.1", + "chalk": "^4.0.0", + "jest-get-type": "^29.2.0", + "jest-util": "^29.2.1", + "pretty-format": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-environment-node": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.2.2.tgz", + "integrity": "sha512-B7qDxQjkIakQf+YyrqV5dICNs7tlCO55WJ4OMSXsqz1lpI/0PmeuXdx2F7eU8rnPbRkUR/fItSSUh0jvE2y/tw==", + "dependencies": { + "@jest/environment": "^29.2.2", + "@jest/fake-timers": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/node": "*", + "jest-mock": "^29.2.2", + "jest-util": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-get-type": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.2.0.tgz", + "integrity": "sha512-uXNJlg8hKFEnDgFsrCjznB+sTxdkuqiCL6zMgA75qEbAJjJYTs9XPrvDctrEig2GDow22T/LvHgO57iJhXB/UA==", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-haste-map": { + "version": "29.2.1", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.2.1.tgz", + "integrity": "sha512-wF460rAFmYc6ARcCFNw4MbGYQjYkvjovb9GBT+W10Um8q5nHq98jD6fHZMDMO3tA56S8XnmNkM8GcA8diSZfnA==", + "dependencies": { + "@jest/types": "^29.2.1", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.2.0", + "jest-util": "^29.2.1", + "jest-worker": "^29.2.1", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "optionalDependencies": { + "fsevents": "^2.3.2" + } + }, + "node_modules/jest-leak-detector": { + "version": "29.2.1", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.2.1.tgz", + "integrity": "sha512-1YvSqYoiurxKOJtySc+CGVmw/e1v4yNY27BjWTVzp0aTduQeA7pdieLiW05wTYG/twlKOp2xS/pWuikQEmklug==", + "dependencies": { + "jest-get-type": "^29.2.0", + "pretty-format": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-matcher-utils": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.2.2.tgz", + "integrity": "sha512-4DkJ1sDPT+UX2MR7Y3od6KtvRi9Im1ZGLGgdLFLm4lPexbTaCgJW5NN3IOXlQHF7NSHY/VHhflQ+WoKtD/vyCw==", + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.2.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-message-util": { + "version": "29.2.1", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.2.1.tgz", + "integrity": "sha512-Dx5nEjw9V8C1/Yj10S/8ivA8F439VS8vTq1L7hEgwHFn9ovSKNpYW/kwNh7UglaEgXO42XxzKJB+2x0nSglFVw==", + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.2.1", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.2.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-mock": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.2.2.tgz", + "integrity": "sha512-1leySQxNAnivvbcx0sCB37itu8f4OX2S/+gxLAV4Z62shT4r4dTG9tACDywUAEZoLSr36aYUTsVp3WKwWt4PMQ==", + "dependencies": { + "@jest/types": "^29.2.1", + "@types/node": "*", + "jest-util": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-pnp-resolver": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz", + "integrity": "sha512-olV41bKSMm8BdnuMsewT4jqlZ8+3TCARAXjZGT9jcoSnrfUnRCqnMoF9XEeoWjbzObpqF9dRhHQj0Xb9QdF6/w==", + "engines": { + "node": ">=6" + }, + "peerDependencies": { + "jest-resolve": "*" + }, + "peerDependenciesMeta": { + "jest-resolve": { + "optional": true + } + } + }, + "node_modules/jest-regex-util": { + "version": "29.2.0", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.2.0.tgz", + "integrity": "sha512-6yXn0kg2JXzH30cr2NlThF+70iuO/3irbaB4mh5WyqNIvLLP+B6sFdluO1/1RJmslyh/f9osnefECflHvTbwVA==", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.2.2.tgz", + "integrity": "sha512-3gaLpiC3kr14rJR3w7vWh0CBX2QAhfpfiQTwrFPvVrcHe5VUBtIXaR004aWE/X9B2CFrITOQAp5gxLONGrk6GA==", + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.2.1", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.2.1", + "jest-validate": "^29.2.2", + "resolve": "^1.20.0", + "resolve.exports": "^1.1.0", + "slash": "^3.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-resolve-dependencies": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.2.2.tgz", + "integrity": "sha512-wWOmgbkbIC2NmFsq8Lb+3EkHuW5oZfctffTGvwsA4JcJ1IRk8b2tg+hz44f0lngvRTeHvp3Kyix9ACgudHH9aQ==", + "dependencies": { + "jest-regex-util": "^29.2.0", + "jest-snapshot": "^29.2.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runner": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.2.2.tgz", + "integrity": "sha512-1CpUxXDrbsfy9Hr9/1zCUUhT813kGGK//58HeIw/t8fa/DmkecEwZSWlb1N/xDKXg3uCFHQp1GCvlSClfImMxg==", + "dependencies": { + "@jest/console": "^29.2.1", + "@jest/environment": "^29.2.2", + "@jest/test-result": "^29.2.1", + "@jest/transform": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.2.0", + "jest-environment-node": "^29.2.2", + "jest-haste-map": "^29.2.1", + "jest-leak-detector": "^29.2.1", + "jest-message-util": "^29.2.1", + "jest-resolve": "^29.2.2", + "jest-runtime": "^29.2.2", + "jest-util": "^29.2.1", + "jest-watcher": "^29.2.2", + "jest-worker": "^29.2.1", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-runtime": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.2.2.tgz", + "integrity": "sha512-TpR1V6zRdLynckKDIQaY41od4o0xWL+KOPUCZvJK2bu5P1UXhjobt5nJ2ICNeIxgyj9NGkO0aWgDqYPVhDNKjA==", + "dependencies": { + "@jest/environment": "^29.2.2", + "@jest/fake-timers": "^29.2.2", + "@jest/globals": "^29.2.2", + "@jest/source-map": "^29.2.0", + "@jest/test-result": "^29.2.1", + "@jest/transform": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.2.1", + "jest-message-util": "^29.2.1", + "jest-mock": "^29.2.2", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.2.2", + "jest-snapshot": "^29.2.2", + "jest-util": "^29.2.1", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-snapshot": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.2.2.tgz", + "integrity": "sha512-GfKJrpZ5SMqhli3NJ+mOspDqtZfJBryGA8RIBxF+G+WbDoC7HCqKaeAss4Z/Sab6bAW11ffasx8/vGsj83jyjA==", + "dependencies": { + "@babel/core": "^7.11.6", + "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", + "@babel/plugin-syntax-typescript": "^7.7.2", + "@babel/traverse": "^7.7.2", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.2.2", + "@jest/transform": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/babel__traverse": "^7.0.6", + "@types/prettier": "^2.1.5", + "babel-preset-current-node-syntax": "^1.0.0", + "chalk": "^4.0.0", + "expect": "^29.2.2", + "graceful-fs": "^4.2.9", + "jest-diff": "^29.2.1", + "jest-get-type": "^29.2.0", + "jest-haste-map": "^29.2.1", + "jest-matcher-utils": "^29.2.2", + "jest-message-util": "^29.2.1", + "jest-util": "^29.2.1", + "natural-compare": "^1.4.0", + "pretty-format": "^29.2.1", + "semver": "^7.3.5" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-snapshot/node_modules/semver": { + "version": "7.3.8", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.8.tgz", + "integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/jest-util": { + "version": "29.2.1", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.2.1.tgz", + "integrity": "sha512-P5VWDj25r7kj7kl4pN2rG/RN2c1TLfYYYZYULnS/35nFDjBai+hBeo3MDrYZS7p6IoY3YHZnt2vq4L6mKnLk0g==", + "dependencies": { + "@jest/types": "^29.2.1", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-validate": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.2.2.tgz", + "integrity": "sha512-eJXATaKaSnOuxNfs8CLHgdABFgUrd0TtWS8QckiJ4L/QVDF4KVbZFBBOwCBZHOS0Rc5fOxqngXeGXE3nGQkpQA==", + "dependencies": { + "@jest/types": "^29.2.1", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.2.0", + "leven": "^3.1.0", + "pretty-format": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-validate/node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-watcher": { + "version": "29.2.2", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.2.2.tgz", + "integrity": "sha512-j2otfqh7mOvMgN2WlJ0n7gIx9XCMWntheYGlBK7+5g3b1Su13/UAK7pdKGyd4kDlrLwtH2QPvRv5oNIxWvsJ1w==", + "dependencies": { + "@jest/test-result": "^29.2.1", + "@jest/types": "^29.2.1", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "jest-util": "^29.2.1", + "string-length": "^4.0.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker": { + "version": "29.2.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.2.1.tgz", + "integrity": "sha512-ROHTZ+oj7sBrgtv46zZ84uWky71AoYi0vEV9CdEtc1FQunsoAGe5HbQmW76nI5QWdvECVPrSi1MCVUmizSavMg==", + "dependencies": { + "@types/node": "*", + "jest-util": "^29.2.1", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/jest-worker/node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "node_modules/js-yaml": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", + "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==" + }, + "node_modules/json5": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.1.tgz", + "integrity": "sha512-1hqLFMSrGHRHxav9q9gNjJ5EXznIxGVO09xQRrwplcS8qs28pZ8s8hupZAmqDwZUmVZ2Qb2jnyPOWcDH8m8dlA==", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/kleur": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", + "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", + "engines": { + "node": ">=6" + } + }, + "node_modules/leven": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", + "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", + "engines": { + "node": ">=6" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==" + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/makeerror": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", + "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", + "dependencies": { + "tmpl": "1.0.5" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==" + }, + "node_modules/micromatch": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", + "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "dependencies": { + "braces": "^3.0.2", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==" + }, + "node_modules/node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==" + }, + "node_modules/node-releases": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.6.tgz", + "integrity": "sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg==" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", + "dependencies": { + "path-key": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-locate/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "engines": { + "node": ">=8" + } + }, + "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==" + }, + "node_modules/picocolors": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", + "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.5.tgz", + "integrity": "sha512-8V9+HQPupnaXMA23c5hvl69zXvTwTzyAYasnkb0Tts4XvO4CliqONMOnvlq26rkhLC3nWDFBJf73LU1e1VZLaQ==", + "engines": { + "node": ">= 6" + } + }, + "node_modules/pkg-dir": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", + "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", + "dependencies": { + "find-up": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pretty-format": { + "version": "29.2.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.2.1.tgz", + "integrity": "sha512-Y41Sa4aLCtKAXvwuIpTvcFBkyeYp2gdFWzXGA+ZNES3VwURIB165XO/z7CjETwzCCS53MjW/rLMyyqEnTtaOfA==", + "dependencies": { + "@jest/schemas": "^29.0.0", + "ansi-styles": "^5.0.0", + "react-is": "^18.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/prompts": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", + "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", + "dependencies": { + "kleur": "^3.0.3", + "sisteransi": "^1.0.5" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/react-is": { + "version": "18.2.0", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", + "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==" + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.1", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.1.tgz", + "integrity": "sha512-nBpuuYuY5jFsli/JIs1oldw6fOQCBioohqWZg/2hiaOybXOft4lonv85uDOKXdf8rhyK159cxU5cDcK/NKk8zw==", + "dependencies": { + "is-core-module": "^2.9.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-cwd": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", + "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "dependencies": { + "resolve-from": "^5.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve-from": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", + "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "engines": { + "node": ">=8" + } + }, + "node_modules/resolve.exports": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-1.1.0.tgz", + "integrity": "sha512-J1l+Zxxp4XK3LUDZ9m60LRJF/mAe4z6a4xyabPHk7pvK5t35dACV32iIjJDFeWZFfZlO29w6SZ67knR0tHzJtQ==", + "engines": { + "node": ">=10" + } + }, + "node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==" + }, + "node_modules/slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", + "engines": { + "node": ">=8" + } + }, + "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-support": { + "version": "0.5.13", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", + "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/sprintf-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==" + }, + "node_modules/stack-utils": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.5.tgz", + "integrity": "sha512-xrQcmYhOsn/1kX+Vraq+7j4oE2j/6BFscZ0etmYg81xuM8Gq0022Pxb8+IqgOFUIaxHs0KaSb7T1+OegiNrNFA==", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/string-length": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", + "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", + "dependencies": { + "char-regex": "^1.0.2", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-bom": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", + "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "engines": { + "node": ">=6" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/test-exclude": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", + "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "dependencies": { + "@istanbuljs/schema": "^0.1.2", + "glob": "^7.1.4", + "minimatch": "^3.0.4" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tmpl": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", + "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==" + }, + "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": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "engines": { + "node": ">=4" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "engines": { + "node": ">=4" + } + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.10.tgz", + "integrity": "sha512-OztqDenkfFkbSG+tRxBeAnCVPckDBcvibKd35yDONx6OU8N7sqgwc7rCbkJ/WcYtVRZ4ba68d6byhC21GFh7sQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + } + ], + "dependencies": { + "escalade": "^3.1.1", + "picocolors": "^1.0.0" + }, + "bin": { + "browserslist-lint": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/v8-to-istanbul": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.0.1.tgz", + "integrity": "sha512-74Y4LqY74kLE6IFyIjPtkSTWzUZmj8tdHT9Ii/26dvQ6K9Dl2NbEfj0XgU2sHCtKgt5VupqhlO/5aWuqS+IY1w==", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.12", + "@types/istanbul-lib-coverage": "^2.0.1", + "convert-source-map": "^1.6.0" + }, + "engines": { + "node": ">=10.12.0" + } + }, + "node_modules/walker": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", + "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", + "dependencies": { + "makeerror": "1.0.12" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" + }, + "node_modules/write-file-atomic": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", + "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.7" + }, + "engines": { + "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, + "node_modules/yargs": { + "version": "17.6.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.6.0.tgz", + "integrity": "sha512-8H/wTDqlSwoSnScvV2N/JHfLWOKuh5MVla9hqLjK3nsfyy6Y4kDSYSvkU5YCUEPOSnRXfIyx3Sq+B/IWudTo4g==", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "engines": { + "node": ">=12" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/node_modules/@ampproject/remapping/LICENSE b/node_modules/@ampproject/remapping/LICENSE new file mode 100644 index 0000000..f367dfb --- /dev/null +++ b/node_modules/@ampproject/remapping/LICENSE @@ -0,0 +1,202 @@ + + 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. diff --git a/node_modules/@ampproject/remapping/README.md b/node_modules/@ampproject/remapping/README.md new file mode 100644 index 0000000..1463c9f --- /dev/null +++ b/node_modules/@ampproject/remapping/README.md @@ -0,0 +1,218 @@ +# @ampproject/remapping + +> Remap sequential sourcemaps through transformations to point at the original source code + +Remapping allows you to take the sourcemaps generated through transforming your code and "remap" +them to the original source locations. Think "my minified code, transformed with babel and bundled +with webpack", all pointing to the correct location in your original source code. + +With remapping, none of your source code transformations need to be aware of the input's sourcemap, +they only need to generate an output sourcemap. This greatly simplifies building custom +transformations (think a find-and-replace). + +## Installation + +```sh +npm install @ampproject/remapping +``` + +## Usage + +```typescript +function remapping( + map: SourceMap | SourceMap[], + loader: (file: string, ctx: LoaderContext) => (SourceMap | null | undefined), + options?: { excludeContent: boolean, decodedMappings: boolean } +): SourceMap; + +// LoaderContext gives the loader the importing sourcemap, tree depth, the ability to override the +// "source" location (where child sources are resolved relative to, or the location of original +// source), and the ability to override the "content" of an original source for inclusion in the +// output sourcemap. +type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +} +``` + +`remapping` takes the final output sourcemap, and a `loader` function. For every source file pointer +in the sourcemap, the `loader` will be called with the resolved path. If the path itself represents +a transformed file (it has a sourcmap associated with it), then the `loader` should return that +sourcemap. If not, the path will be treated as an original, untransformed source code. + +```js +// Babel transformed "helloworld.js" into "transformed.js" +const transformedMap = JSON.stringify({ + file: 'transformed.js', + // 1st column of 2nd line of output file translates into the 1st source + // file, line 3, column 2 + mappings: ';CAEE', + sources: ['helloworld.js'], + version: 3, +}); + +// Uglify minified "transformed.js" into "transformed.min.js" +const minifiedTransformedMap = JSON.stringify({ + file: 'transformed.min.js', + // 0th column of 1st line of output file translates into the 1st source + // file, line 2, column 1. + mappings: 'AACC', + names: [], + sources: ['transformed.js'], + version: 3, +}); + +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + // The "transformed.js" file is an transformed file. + if (file === 'transformed.js') { + // The root importer is empty. + console.assert(ctx.importer === ''); + // The depth in the sourcemap tree we're currently loading. + // The root `minifiedTransformedMap` is depth 0, and its source children are depth 1, etc. + console.assert(ctx.depth === 1); + + return transformedMap; + } + + // Loader will be called to load transformedMap's source file pointers as well. + console.assert(file === 'helloworld.js'); + // `transformed.js`'s sourcemap points into `helloworld.js`. + console.assert(ctx.importer === 'transformed.js'); + // This is a source child of `transformed`, which is a source child of `minifiedTransformedMap`. + console.assert(ctx.depth === 2); + return null; + } +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +In this example, `loader` will be called twice: + +1. `"transformed.js"`, the first source file pointer in the `minifiedTransformedMap`. We return the + associated sourcemap for it (its a transformed file, after all) so that sourcemap locations can + be traced through it into the source files it represents. +2. `"helloworld.js"`, our original, unmodified source code. This file does not have a sourcemap, so + we return `null`. + +The `remapped` sourcemap now points from `transformed.min.js` into locations in `helloworld.js`. If +you were to read the `mappings`, it says "0th column of the first line output line points to the 1st +column of the 2nd line of the file `helloworld.js`". + +### Multiple transformations of a file + +As a convenience, if you have multiple single-source transformations of a file, you may pass an +array of sourcemap files in the order of most-recent transformation sourcemap first. Note that this +changes the `importer` and `depth` of each call to our loader. So our above example could have been +written as: + +```js +const remapped = remapping( + [minifiedTransformedMap, transformedMap], + () => null +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +### Advanced control of the loading graph + +#### `source` + +The `source` property can overridden to any value to change the location of the current load. Eg, +for an original source file, it allows us to change the location to the original source regardless +of what the sourcemap source entry says. And for transformed files, it allows us to change the +relative resolving location for child sources of the loaded sourcemap. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // We pretend the transformed.js file actually exists in the 'src/' directory. When the nested + // source files are loaded, they will now be relative to `src/`. + ctx.source = 'src/transformed.js'; + return transformedMap; + } + + console.assert(file === 'src/helloworld.js'); + // We could futher change the source of this original file, eg, to be inside a nested directory + // itself. This will be reflected in the remapped sourcemap. + ctx.source = 'src/nested/transformed.js'; + return null; + } +); + +console.log(remapped); +// { +// …, +// sources: ['src/nested/helloworld.js'], +// }; +``` + + +#### `content` + +The `content` property can be overridden when we encounter an original source file. Eg, this allows +you to manually provide the source content of the original file regardless of whether the +`sourcesContent` field is present in the parent sourcemap. It can also be set to `null` to remove +the source content. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // transformedMap does not include a `sourcesContent` field, so usually the remapped sourcemap + // would not include any `sourcesContent` values. + return transformedMap; + } + + console.assert(file === 'helloworld.js'); + // We can read the file to provide the source content. + ctx.content = fs.readFileSync(file, 'utf8'); + return null; + } +); + +console.log(remapped); +// { +// …, +// sourcesContent: [ +// 'console.log("Hello world!")', +// ], +// }; +``` + +### Options + +#### excludeContent + +By default, `excludeContent` is `false`. Passing `{ excludeContent: true }` will exclude the +`sourcesContent` field from the returned sourcemap. This is mainly useful when you want to reduce +the size out the sourcemap. + +#### decodedMappings + +By default, `decodedMappings` is `false`. Passing `{ decodedMappings: true }` will leave the +`mappings` field in a [decoded state](https://github.com/rich-harris/sourcemap-codec) instead of +encoding into a VLQ string. diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs b/node_modules/@ampproject/remapping/dist/remapping.mjs new file mode 100644 index 0000000..c6e66b7 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs @@ -0,0 +1,204 @@ +import { decodedMappings, traceSegment, TraceMap } from '@jridgewell/trace-mapping'; +import { GenMapping, addSegment, setSourceContent, decodedMap, encodedMap } from '@jridgewell/gen-mapping'; + +const SOURCELESS_MAPPING = { + source: null, + column: null, + line: null, + name: null, + content: null, +}; +const EMPTY_SOURCES = []; +function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; +} +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +function MapSource(map, sources) { + return Source(map, sources, '', null); +} +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); +} +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +function traceMappings(tree) { + const gen = new GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + let lastSource = null; + let lastSourceLine = null; + let lastSourceColumn = null; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + 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, content, source } = traced; + if (line === lastSourceLine && column === lastSourceColumn && source === lastSource) { + continue; + } + lastSourceLine = line; + lastSourceColumn = column; + lastSource = source; + // Sigh, TypeScript can't figure out source/line/column are either all null, or all non-null... + addSegment(gen, i, genCol, source, line, column, name); + if (content != null) + setSourceContent(gen, source, content); + } + } + return gen; +} +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +function originalPositionFor(source, line, column, name) { + if (!source.map) { + return { column, line, name, source: source.source, content: source.content }; + } + const segment = traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); +} + +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) { + const maps = asArray(input).map((m) => new TraceMap(m, '')); + 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?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} +function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); +} + +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? decodedMap(map) : encodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +} + +/** + * 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 tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} + +export { remapping as default }; +//# sourceMappingURL=remapping.mjs.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.mjs.map b/node_modules/@ampproject/remapping/dist/remapping.mjs.map new file mode 100644 index 0000000..54066bb --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.mjs","sources":["../../src/source-map-tree.ts","../../src/build-source-map-tree.ts","../../src/source-map.ts","../../src/remapping.ts"],"sourcesContent":[null,null,null,null],"names":[],"mappings":";;;AAqBA,MAAM,kBAAkB,GAAG;AACzB,IAAA,MAAM,EAAE,IAAI;AACZ,IAAA,MAAM,EAAE,IAAI;AACZ,IAAA,IAAI,EAAE,IAAI;AACV,IAAA,IAAI,EAAE,IAAI;AACV,IAAA,OAAO,EAAE,IAAI;CACd,CAAC;AACF,MAAM,aAAa,GAAc,EAAE,CAAC;AAkBpC,SAAS,MAAM,CACb,GAAoB,EACpB,OAAkB,EAClB,MAAc,EACd,OAAsB,EAAA;IAEtB,OAAO;QACL,GAAG;QACH,OAAO;QACP,MAAM;QACN,OAAO;KACD,CAAC;AACX,CAAC;AAED;;;AAGG;AACa,SAAA,SAAS,CAAC,GAAa,EAAE,OAAkB,EAAA;IACzD,OAAO,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;AACxC,CAAC;AAED;;;AAGG;AACa,SAAA,cAAc,CAAC,MAAc,EAAE,OAAsB,EAAA;IACnE,OAAO,MAAM,CAAC,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AACtD,CAAC;AAED;;;AAGG;AACG,SAAU,aAAa,CAAC,IAAe,EAAA;AAC3C,IAAA,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;IACpD,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC3C,IAAA,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,CAAC;AAC5B,IAAA,MAAM,YAAY,GAAG,eAAe,CAAC,GAAG,CA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UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;AAEjC,QAAA,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,OAA+B,CAAC;AACnD,QAAA,IAAI,CAAC,OAAO,CAAC,cAAc,EAAE;AAC3B,YAAA,IAAI,CAAC,cAAc,GAAG,GAAG,CAAC,cAA6C,CAAC;AACzE,SAAA;KACF;IAED,QAAQ,GAAA;AACN,QAAA,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;KAC7B;AACF;;ACpBD;;;;;;;;;;;;;;AAcG;AACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;IAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;IAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AAClD;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js b/node_modules/@ampproject/remapping/dist/remapping.umd.js new file mode 100644 index 0000000..593c61d --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js @@ -0,0 +1,209 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@jridgewell/trace-mapping'), require('@jridgewell/gen-mapping')) : + typeof define === 'function' && define.amd ? define(['@jridgewell/trace-mapping', '@jridgewell/gen-mapping'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.remapping = factory(global.traceMapping, global.genMapping)); +})(this, (function (traceMapping, genMapping) { 'use strict'; + + const SOURCELESS_MAPPING = { + source: null, + column: null, + line: null, + name: null, + content: null, + }; + const EMPTY_SOURCES = []; + function Source(map, sources, source, content) { + return { + map, + sources, + source, + content, + }; + } + /** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ + function MapSource(map, sources) { + return Source(map, sources, '', null); + } + /** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ + function OriginalSource(source, content) { + return Source(null, EMPTY_SOURCES, source, content); + } + /** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ + function traceMappings(tree) { + const gen = new genMapping.GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = traceMapping.decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + let lastSource = null; + let lastSourceLine = null; + let lastSourceColumn = null; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : ''); + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) + 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, content, source } = traced; + if (line === lastSourceLine && column === lastSourceColumn && source === lastSource) { + continue; + } + lastSourceLine = line; + lastSourceColumn = column; + lastSource = source; + // Sigh, TypeScript can't figure out source/line/column are either all null, or all non-null... + genMapping.addSegment(gen, i, genCol, source, line, column, name); + if (content != null) + genMapping.setSourceContent(gen, source, content); + } + } + return gen; + } + /** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ + function originalPositionFor(source, line, column, name) { + if (!source.map) { + return { column, line, name, source: source.source, content: source.content }; + } + const segment = traceMapping.traceSegment(source.map, line, column); + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) + return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) + return SOURCELESS_MAPPING; + return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name); + } + + 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) { + const maps = asArray(input).map((m) => new traceMapping.TraceMap(m, '')); + 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?'); + } + } + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; + } + function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx = { + importer, + depth, + source: sourceFile || '', + content: undefined, + }; + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + const { source, content } = ctx; + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) + return build(new traceMapping.TraceMap(sourceMap, source), loader, source, depth); + // Else, it's an an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + return OriginalSource(source, sourceContent); + }); + return MapSource(map, children); + } + + /** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ + class SourceMap { + constructor(map, options) { + const out = options.decodedMappings ? genMapping.decodedMap(map) : genMapping.encodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } + } + + /** + * 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 tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); + } + + return remapping; + +})); +//# sourceMappingURL=remapping.umd.js.map diff --git a/node_modules/@ampproject/remapping/dist/remapping.umd.js.map b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map new file mode 100644 index 0000000..726f2bc --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/remapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.umd.js","sources":["../../src/source-map-tree.ts","../../src/build-source-map-tree.ts","../../src/source-map.ts","../../src/remapping.ts"],"sourcesContent":[null,null,null,null],"names":["GenMapping","decodedMappings","addSegment","setSourceContent","traceSegment","TraceMap","decodedMap","encodedMap"],"mappings":";;;;;;IAqBA,MAAM,kBAAkB,GAAG;IACzB,IAAA,MAAM,EAAE,IAAI;IACZ,IAAA,MAAM,EAAE,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IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;SAC7B;IACF;;ICpBD;;;;;;;;;;;;;;IAcG;IACqB,SAAA,SAAS,CAC/B,KAAwC,EACxC,MAAuB,EACvB,OAA2B,EAAA;QAE3B,MAAM,IAAI,GACR,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,GAAG,EAAE,cAAc,EAAE,CAAC,CAAC,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC;QAChG,MAAM,IAAI,GAAG,kBAAkB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAC/C,OAAO,IAAI,SAAS,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;IAClD;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts new file mode 100644 index 0000000..f87fcea --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/build-source-map-tree.d.ts @@ -0,0 +1,14 @@ +import type { MapSource as MapSourceType } from './source-map-tree'; +import type { SourceMapInput, SourceMapLoader } from './types'; +/** + * 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. + */ +export default function buildSourceMapTree(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader): MapSourceType; diff --git a/node_modules/@ampproject/remapping/dist/types/remapping.d.ts b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts new file mode 100644 index 0000000..0b58ea9 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/remapping.d.ts @@ -0,0 +1,19 @@ +import SourceMap from './source-map'; +import type { SourceMapInput, SourceMapLoader, Options } from './types'; +export type { SourceMapSegment, EncodedSourceMap, EncodedSourceMap as RawSourceMap, DecodedSourceMap, SourceMapInput, SourceMapLoader, LoaderContext, Options, } from './types'; +/** + * 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. + */ +export default function remapping(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader, options?: boolean | Options): SourceMap; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts new file mode 100644 index 0000000..3b6b1bf --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map-tree.d.ts @@ -0,0 +1,48 @@ +import { GenMapping } from '@jridgewell/gen-mapping'; +import type { TraceMap } from '@jridgewell/trace-mapping'; +export declare type SourceMapSegmentObject = { + column: number; + line: number; + name: string; + source: string; + content: string | null; +} | { + column: null; + line: null; + name: null; + source: null; + content: null; +}; +export declare type OriginalSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: string | null; +}; +export declare type MapSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: string | null; +}; +export declare type Sources = OriginalSource | MapSource; +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +export declare function MapSource(map: TraceMap, sources: Sources[]): MapSource; +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +export declare function OriginalSource(source: string, content: string | null): OriginalSource; +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +export declare function traceMappings(tree: MapSource): GenMapping; +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +export declare function originalPositionFor(source: Sources, line: number, column: number, name: string): SourceMapSegmentObject | null; diff --git a/node_modules/@ampproject/remapping/dist/types/source-map.d.ts b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts new file mode 100644 index 0000000..ef999b7 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/source-map.d.ts @@ -0,0 +1,17 @@ +import type { GenMapping } from '@jridgewell/gen-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Options } from './types'; +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +export default class SourceMap { + file?: string | null; + mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings']; + sourceRoot?: string; + names: string[]; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + constructor(map: GenMapping, options: Options); + toString(): string; +} diff --git a/node_modules/@ampproject/remapping/dist/types/types.d.ts b/node_modules/@ampproject/remapping/dist/types/types.d.ts new file mode 100644 index 0000000..730a963 --- /dev/null +++ b/node_modules/@ampproject/remapping/dist/types/types.d.ts @@ -0,0 +1,14 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +export type { SourceMapSegment, DecodedSourceMap, EncodedSourceMap, } from '@jridgewell/trace-mapping'; +export type { SourceMapInput }; +export declare type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +}; +export declare type SourceMapLoader = (file: string, ctx: LoaderContext) => SourceMapInput | null | undefined | void; +export declare type Options = { + excludeContent?: boolean; + decodedMappings?: boolean; +}; diff --git a/node_modules/@ampproject/remapping/package.json b/node_modules/@ampproject/remapping/package.json new file mode 100644 index 0000000..bf97a85 --- /dev/null +++ b/node_modules/@ampproject/remapping/package.json @@ -0,0 +1,63 @@ +{ + "name": "@ampproject/remapping", + "version": "2.2.0", + "description": "Remap sequential sourcemaps through transformations to point at the original source code", + "keywords": [ + "source", + "map", + "remap" + ], + "main": "dist/remapping.umd.js", + "module": "dist/remapping.mjs", + "typings": "dist/types/remapping.d.ts", + "files": [ + "dist" + ], + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/ampproject/remapping.git" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "node --inspect-brk node_modules/.bin/jest --runInBand", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "jest --coverage", + "test:watch": "jest --coverage --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.2", + "@types/jest": "27.4.1", + "@typescript-eslint/eslint-plugin": "5.20.0", + "@typescript-eslint/parser": "5.20.0", + "eslint": "8.14.0", + "eslint-config-prettier": "8.5.0", + "jest": "27.5.1", + "jest-config": "27.5.1", + "npm-run-all": "4.1.5", + "prettier": "2.6.2", + "rollup": "2.70.2", + "ts-jest": "27.1.4", + "tslib": "2.4.0", + "typescript": "4.6.3" + }, + "dependencies": { + "@jridgewell/gen-mapping": "^0.1.0", + "@jridgewell/trace-mapping": "^0.3.9" + } +} diff --git a/node_modules/@babel/code-frame/LICENSE b/node_modules/@babel/code-frame/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/code-frame/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/code-frame/README.md b/node_modules/@babel/code-frame/README.md new file mode 100644 index 0000000..08cacb0 --- /dev/null +++ b/node_modules/@babel/code-frame/README.md @@ -0,0 +1,19 @@ +# @babel/code-frame + +> Generate errors that contain a code frame that point to source locations. + +See our website [@babel/code-frame](https://babeljs.io/docs/en/babel-code-frame) for more information. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/code-frame +``` + +or using yarn: + +```sh +yarn add @babel/code-frame --dev +``` diff --git a/node_modules/@babel/code-frame/lib/index.js b/node_modules/@babel/code-frame/lib/index.js new file mode 100644 index 0000000..cba3f83 --- /dev/null +++ b/node_modules/@babel/code-frame/lib/index.js @@ -0,0 +1,163 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.codeFrameColumns = codeFrameColumns; +exports.default = _default; + +var _highlight = require("@babel/highlight"); + +let deprecationWarningShown = false; + +function getDefs(chalk) { + return { + gutter: chalk.grey, + marker: chalk.red.bold, + message: chalk.red.bold + }; +} + +const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + +function getMarkerLines(loc, source, opts) { + const startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + const endLoc = Object.assign({}, startLoc, loc.end); + const { + linesAbove = 2, + linesBelow = 3 + } = opts || {}; + const startLine = startLoc.line; + const startColumn = startLoc.column; + const endLine = endLoc.line; + const endColumn = endLoc.column; + let start = Math.max(startLine - (linesAbove + 1), 0); + let end = Math.min(source.length, endLine + linesBelow); + + if (startLine === -1) { + start = 0; + } + + if (endLine === -1) { + end = source.length; + } + + const lineDiff = endLine - startLine; + const markerLines = {}; + + if (lineDiff) { + for (let i = 0; i <= lineDiff; i++) { + const lineNumber = i + startLine; + + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + const sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + const sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, sourceLength]; + } + } + } else { + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } + } + + return { + start, + end, + markerLines + }; +} + +function codeFrameColumns(rawLines, loc, opts = {}) { + const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); + const chalk = (0, _highlight.getChalk)(opts); + const defs = getDefs(chalk); + + const maybeHighlight = (chalkFn, string) => { + return highlighted ? chalkFn(string) : string; + }; + + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end).length; + const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; + let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number}`.slice(-numberMaxWidth); + const gutter = ` ${paddedNumber} |`; + const hasMarker = markerLines[number]; + const lastMarkerLine = !markerLines[number + 1]; + + if (hasMarker) { + let markerLine = ""; + + if (Array.isArray(hasMarker)) { + const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + const numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), " ", markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); + + if (lastMarkerLine && opts.message) { + markerLine += " " + maybeHighlight(defs.message, opts.message); + } + } + + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line.length > 0 ? ` ${line}` : "", markerLine].join(""); + } else { + return ` ${maybeHighlight(defs.gutter, gutter)}${line.length > 0 ? ` ${line}` : ""}`; + } + }).join("\n"); + + if (opts.message && !hasColumns) { + frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; + } + + if (highlighted) { + return chalk.reset(frame); + } else { + return frame; + } +} + +function _default(rawLines, lineNumber, colNumber, opts = {}) { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; + + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + const deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + + colNumber = Math.max(colNumber, 0); + const location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); +} \ No newline at end of file diff --git a/node_modules/@babel/code-frame/package.json b/node_modules/@babel/code-frame/package.json new file mode 100644 index 0000000..18d8db1 --- /dev/null +++ b/node_modules/@babel/code-frame/package.json @@ -0,0 +1,30 @@ +{ + "name": "@babel/code-frame", + "version": "7.18.6", + "description": "Generate errors that contain a code frame that point to source locations.", + "author": "The Babel Team (https://babel.dev/team)", + "homepage": "https://babel.dev/docs/en/next/babel-code-frame", + "bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-code-frame" + }, + "main": "./lib/index.js", + "dependencies": { + "@babel/highlight": "^7.18.6" + }, + "devDependencies": { + "@types/chalk": "^2.0.0", + "chalk": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "engines": { + "node": ">=6.9.0" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/compat-data/LICENSE b/node_modules/@babel/compat-data/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/compat-data/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/compat-data/README.md b/node_modules/@babel/compat-data/README.md new file mode 100644 index 0000000..9f3abde --- /dev/null +++ b/node_modules/@babel/compat-data/README.md @@ -0,0 +1,19 @@ +# @babel/compat-data + +> + +See our website [@babel/compat-data](https://babeljs.io/docs/en/babel-compat-data) for more information. + +## Install + +Using npm: + +```sh +npm install --save @babel/compat-data +``` + +or using yarn: + +```sh +yarn add @babel/compat-data +``` diff --git a/node_modules/@babel/compat-data/corejs2-built-ins.js b/node_modules/@babel/compat-data/corejs2-built-ins.js new file mode 100644 index 0000000..68ce97f --- /dev/null +++ b/node_modules/@babel/compat-data/corejs2-built-ins.js @@ -0,0 +1 @@ +module.exports = require("./data/corejs2-built-ins.json"); diff --git a/node_modules/@babel/compat-data/corejs3-shipped-proposals.js b/node_modules/@babel/compat-data/corejs3-shipped-proposals.js new file mode 100644 index 0000000..6a85b4d --- /dev/null +++ b/node_modules/@babel/compat-data/corejs3-shipped-proposals.js @@ -0,0 +1 @@ +module.exports = require("./data/corejs3-shipped-proposals.json"); diff --git a/node_modules/@babel/compat-data/data/corejs2-built-ins.json b/node_modules/@babel/compat-data/data/corejs2-built-ins.json new file mode 100644 index 0000000..b9e4cfe --- /dev/null +++ b/node_modules/@babel/compat-data/data/corejs2-built-ins.json @@ -0,0 +1,1789 @@ +{ + "es6.array.copy-within": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "32", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.31" + }, + "es6.array.every": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.fill": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "31", + "safari": "7.1", + "node": "4", + "ios": "8", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.31" + }, + "es6.array.filter": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.array.find": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "4", + "ios": "8", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.31" + }, + "es6.array.find-index": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "4", + "ios": "8", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.31" + }, + "es7.array.flat-map": { + "chrome": "69", + "opera": "56", + "edge": "79", + "firefox": "62", + "safari": "12", + "node": "11", + "ios": "12", + "samsung": "10", + "electron": "4.0" + }, + "es6.array.for-each": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.from": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "36", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es7.array.includes": { + "chrome": "47", + "opera": "34", + "edge": "14", + "firefox": "102", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "es6.array.index-of": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.is-array": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "4", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.iterator": { + "chrome": "66", + "opera": "53", + "edge": "12", + "firefox": "60", + "safari": "9", + "node": "10", + "ios": "9", + "samsung": "9", + "rhino": "1.7.13", + "electron": "3.0" + }, + "es6.array.last-index-of": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.map": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.array.of": { + "chrome": "45", + "opera": "32", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.31" + }, + "es6.array.reduce": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.reduce-right": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.slice": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.array.some": { + "chrome": "5", + "opera": "10.10", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.array.sort": { + "chrome": "63", + "opera": "50", + "edge": "12", + "firefox": "5", + "safari": "12", + "node": "10", + "ie": "9", + "ios": "12", + "samsung": "8", + "rhino": "1.7.13", + "electron": "3.0" + }, + "es6.array.species": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.date.now": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "2", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.date.to-iso-string": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3.5", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.date.to-json": { + "chrome": "5", + "opera": "12.10", + "edge": "12", + "firefox": "4", + "safari": "10", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "10", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.date.to-primitive": { + "chrome": "47", + "opera": "34", + "edge": "15", + "firefox": "44", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "es6.date.to-string": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.4", + "ie": "10", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.function.bind": { + "chrome": "7", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "5.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.function.has-instance": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "50", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.function.name": { + "chrome": "5", + "opera": "10.50", + "edge": "14", + "firefox": "2", + "safari": "4", + "node": "0.4", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.map": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.math.acosh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.asinh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.atanh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.cbrt": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.clz32": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.cosh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.expm1": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.fround": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "26", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.hypot": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "27", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.imul": { + "chrome": "30", + "opera": "17", + "edge": "12", + "firefox": "23", + "safari": "7", + "node": "0.12", + "android": "4.4", + "ios": "7", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.log1p": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.log10": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.log2": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.sign": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.sinh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.tanh": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.math.trunc": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "25", + "safari": "7.1", + "node": "0.12", + "ios": "8", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.constructor": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "36", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.number.epsilon": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.number.is-finite": { + "chrome": "19", + "opera": "15", + "edge": "12", + "firefox": "16", + "safari": "9", + "node": "0.8", + "android": "4.1", + "ios": "9", + "samsung": "1.5", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.is-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "16", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.is-nan": { + "chrome": "19", + "opera": "15", + "edge": "12", + "firefox": "15", + "safari": "9", + "node": "0.8", + "android": "4.1", + "ios": "9", + "samsung": "1.5", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.is-safe-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "32", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.max-safe-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.min-safe-integer": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.number.parse-float": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.number.parse-int": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "25", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "2", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.object.assign": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "36", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.object.create": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es7.object.define-getter": { + "chrome": "62", + "opera": "49", + "edge": "16", + "firefox": "48", + "safari": "9", + "node": "8.10", + "ios": "9", + "samsung": "8", + "electron": "3.0" + }, + "es7.object.define-setter": { + "chrome": "62", + "opera": "49", + "edge": "16", + "firefox": "48", + "safari": "9", + "node": "8.10", + "ios": "9", + "samsung": "8", + "electron": "3.0" + }, + "es6.object.define-property": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "5.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.object.define-properties": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "4", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es7.object.entries": { + "chrome": "54", + "opera": "41", + "edge": "14", + "firefox": "47", + "safari": "10.1", + "node": "7", + "ios": "10.3", + "samsung": "6", + "rhino": "1.7.14", + "electron": "1.4" + }, + "es6.object.freeze": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.get-own-property-descriptor": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es7.object.get-own-property-descriptors": { + "chrome": "54", + "opera": "41", + "edge": "15", + "firefox": "50", + "safari": "10.1", + "node": "7", + "ios": "10.3", + "samsung": "6", + "electron": "1.4" + }, + "es6.object.get-own-property-names": { + "chrome": "40", + "opera": "27", + "edge": "12", + "firefox": "33", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.object.get-prototype-of": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es7.object.lookup-getter": { + "chrome": "62", + "opera": "49", + "edge": "79", + "firefox": "36", + "safari": "9", + "node": "8.10", + "ios": "9", + "samsung": "8", + "electron": "3.0" + }, + "es7.object.lookup-setter": { + "chrome": "62", + "opera": "49", + "edge": "79", + "firefox": "36", + "safari": "9", + "node": "8.10", + "ios": "9", + "samsung": "8", + "electron": "3.0" + }, + "es6.object.prevent-extensions": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.to-string": { + "chrome": "57", + "opera": "44", + "edge": "15", + "firefox": "51", + "safari": "10", + "node": "8", + "ios": "10", + "samsung": "7", + "electron": "1.7" + }, + "es6.object.is": { + "chrome": "19", + "opera": "15", + "edge": "12", + "firefox": "22", + "safari": "9", + "node": "0.8", + "android": "4.1", + "ios": "9", + "samsung": "1.5", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.object.is-frozen": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.is-sealed": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.is-extensible": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.keys": { + "chrome": "40", + "opera": "27", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.object.seal": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "35", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.13", + "electron": "0.30" + }, + "es6.object.set-prototype-of": { + "chrome": "34", + "opera": "21", + "edge": "12", + "firefox": "31", + "safari": "9", + "node": "0.12", + "ie": "11", + "ios": "9", + "samsung": "2", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es7.object.values": { + "chrome": "54", + "opera": "41", + "edge": "14", + "firefox": "47", + "safari": "10.1", + "node": "7", + "ios": "10.3", + "samsung": "6", + "rhino": "1.7.14", + "electron": "1.4" + }, + "es6.promise": { + "chrome": "51", + "opera": "38", + "edge": "14", + "firefox": "45", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es7.promise.finally": { + "chrome": "63", + "opera": "50", + "edge": "18", + "firefox": "58", + "safari": "11.1", + "node": "10", + "ios": "11.3", + "samsung": "8", + "electron": "3.0" + }, + "es6.reflect.apply": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.construct": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "49", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.define-property": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.delete-property": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.get": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.get-own-property-descriptor": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.get-prototype-of": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.has": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.is-extensible": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.own-keys": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.prevent-extensions": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.set": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.reflect.set-prototype-of": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "42", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "es6.regexp.constructor": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "40", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "1.1" + }, + "es6.regexp.flags": { + "chrome": "49", + "opera": "36", + "edge": "79", + "firefox": "37", + "safari": "9", + "node": "6", + "ios": "9", + "samsung": "5", + "electron": "0.37" + }, + "es6.regexp.match": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "rhino": "1.7.13", + "electron": "1.1" + }, + "es6.regexp.replace": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "1.1" + }, + "es6.regexp.split": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "1.1" + }, + "es6.regexp.search": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "49", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "rhino": "1.7.13", + "electron": "1.1" + }, + "es6.regexp.to-string": { + "chrome": "50", + "opera": "37", + "edge": "79", + "firefox": "39", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "1.1" + }, + "es6.set": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.symbol": { + "chrome": "51", + "opera": "38", + "edge": "79", + "firefox": "51", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es7.symbol.async-iterator": { + "chrome": "63", + "opera": "50", + "edge": "79", + "firefox": "57", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "8", + "electron": "3.0" + }, + "es6.string.anchor": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.big": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.blink": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.bold": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.code-point-at": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.ends-with": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.fixed": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.fontcolor": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.fontsize": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.from-code-point": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.includes": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "40", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.italics": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.iterator": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "36", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.string.link": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es7.string.pad-start": { + "chrome": "57", + "opera": "44", + "edge": "15", + "firefox": "48", + "safari": "10", + "node": "8", + "ios": "10", + "samsung": "7", + "rhino": "1.7.13", + "electron": "1.7" + }, + "es7.string.pad-end": { + "chrome": "57", + "opera": "44", + "edge": "15", + "firefox": "48", + "safari": "10", + "node": "8", + "ios": "10", + "samsung": "7", + "rhino": "1.7.13", + "electron": "1.7" + }, + "es6.string.raw": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "34", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.14", + "electron": "0.21" + }, + "es6.string.repeat": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "24", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.small": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.starts-with": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "29", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "rhino": "1.7.13", + "electron": "0.21" + }, + "es6.string.strike": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.sub": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.sup": { + "chrome": "5", + "opera": "15", + "edge": "12", + "firefox": "17", + "safari": "6", + "node": "0.4", + "android": "4", + "ios": "7", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.14", + "electron": "0.20" + }, + "es6.string.trim": { + "chrome": "5", + "opera": "10.50", + "edge": "12", + "firefox": "3.5", + "safari": "4", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es7.string.trim-left": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "61", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "9", + "rhino": "1.7.13", + "electron": "3.0" + }, + "es7.string.trim-right": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "61", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "9", + "rhino": "1.7.13", + "electron": "3.0" + }, + "es6.typed.array-buffer": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.data-view": { + "chrome": "5", + "opera": "12", + "edge": "12", + "firefox": "15", + "safari": "5.1", + "node": "0.4", + "ie": "10", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "es6.typed.int8-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.uint8-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.uint8-clamped-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.int16-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.uint16-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.int32-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.uint32-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.float32-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.typed.float64-array": { + "chrome": "51", + "opera": "38", + "edge": "13", + "firefox": "48", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "es6.weak-map": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "9", + "node": "6.5", + "ios": "9", + "samsung": "5", + "electron": "1.2" + }, + "es6.weak-set": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "9", + "node": "6.5", + "ios": "9", + "samsung": "5", + "electron": "1.2" + } +} diff --git a/node_modules/@babel/compat-data/data/corejs3-shipped-proposals.json b/node_modules/@babel/compat-data/data/corejs3-shipped-proposals.json new file mode 100644 index 0000000..7ce01ed --- /dev/null +++ b/node_modules/@babel/compat-data/data/corejs3-shipped-proposals.json @@ -0,0 +1,5 @@ +[ + "esnext.global-this", + "esnext.promise.all-settled", + "esnext.string.match-all" +] diff --git a/node_modules/@babel/compat-data/data/native-modules.json b/node_modules/@babel/compat-data/data/native-modules.json new file mode 100644 index 0000000..bf63499 --- /dev/null +++ b/node_modules/@babel/compat-data/data/native-modules.json @@ -0,0 +1,18 @@ +{ + "es6.module": { + "chrome": "61", + "and_chr": "61", + "edge": "16", + "firefox": "60", + "and_ff": "60", + "node": "13.2.0", + "opera": "48", + "op_mob": "48", + "safari": "10.1", + "ios": "10.3", + "samsung": "8.2", + "android": "61", + "electron": "2.0", + "ios_saf": "10.3" + } +} diff --git a/node_modules/@babel/compat-data/data/overlapping-plugins.json b/node_modules/@babel/compat-data/data/overlapping-plugins.json new file mode 100644 index 0000000..94fda05 --- /dev/null +++ b/node_modules/@babel/compat-data/data/overlapping-plugins.json @@ -0,0 +1,25 @@ +{ + "transform-async-to-generator": [ + "bugfix/transform-async-arrows-in-class" + ], + "transform-parameters": [ + "bugfix/transform-edge-default-parameters", + "bugfix/transform-safari-id-destructuring-collision-in-function-expression" + ], + "transform-function-name": [ + "bugfix/transform-edge-function-name" + ], + "transform-block-scoping": [ + "bugfix/transform-safari-block-shadowing", + "bugfix/transform-safari-for-shadowing" + ], + "transform-template-literals": [ + "bugfix/transform-tagged-template-caching" + ], + "transform-optional-chaining": [ + "bugfix/transform-v8-spread-parameters-in-optional-chaining" + ], + "proposal-optional-chaining": [ + "bugfix/transform-v8-spread-parameters-in-optional-chaining" + ] +} diff --git a/node_modules/@babel/compat-data/data/plugin-bugfixes.json b/node_modules/@babel/compat-data/data/plugin-bugfixes.json new file mode 100644 index 0000000..4fbe7dd --- /dev/null +++ b/node_modules/@babel/compat-data/data/plugin-bugfixes.json @@ -0,0 +1,168 @@ +{ + "bugfix/transform-async-arrows-in-class": { + "chrome": "55", + "opera": "42", + "edge": "15", + "firefox": "52", + "safari": "11", + "node": "7.6", + "ios": "11", + "samsung": "6", + "electron": "1.6" + }, + "bugfix/transform-edge-default-parameters": { + "chrome": "49", + "opera": "36", + "edge": "18", + "firefox": "52", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "bugfix/transform-edge-function-name": { + "chrome": "51", + "opera": "38", + "edge": "79", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "bugfix/transform-safari-block-shadowing": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "44", + "safari": "11", + "node": "6", + "ie": "11", + "ios": "11", + "samsung": "5", + "electron": "0.37" + }, + "bugfix/transform-safari-for-shadowing": { + "chrome": "49", + "opera": "36", + "edge": "12", + "firefox": "4", + "safari": "11", + "node": "6", + "ie": "11", + "ios": "11", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.37" + }, + "bugfix/transform-safari-id-destructuring-collision-in-function-expression": { + "chrome": "49", + "opera": "36", + "edge": "14", + "firefox": "2", + "node": "6", + "samsung": "5", + "electron": "0.37" + }, + "bugfix/transform-tagged-template-caching": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "34", + "safari": "13", + "node": "4", + "ios": "13", + "samsung": "3.4", + "rhino": "1.7.14", + "electron": "0.21" + }, + "bugfix/transform-v8-spread-parameters-in-optional-chaining": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "74", + "safari": "13.1", + "node": "16.9", + "ios": "13.4", + "electron": "13.0" + }, + "transform-optional-chaining": { + "chrome": "80", + "opera": "67", + "edge": "80", + "firefox": "74", + "safari": "13.1", + "node": "14", + "ios": "13.4", + "samsung": "13", + "electron": "8.0" + }, + "proposal-optional-chaining": { + "chrome": "80", + "opera": "67", + "edge": "80", + "firefox": "74", + "safari": "13.1", + "node": "14", + "ios": "13.4", + "samsung": "13", + "electron": "8.0" + }, + "transform-parameters": { + "chrome": "49", + "opera": "36", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "transform-async-to-generator": { + "chrome": "55", + "opera": "42", + "edge": "15", + "firefox": "52", + "safari": "10.1", + "node": "7.6", + "ios": "10.3", + "samsung": "6", + "electron": "1.6" + }, + "transform-template-literals": { + "chrome": "41", + "opera": "28", + "edge": "13", + "firefox": "34", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "electron": "0.21" + }, + "transform-function-name": { + "chrome": "51", + "opera": "38", + "edge": "14", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "transform-block-scoping": { + "chrome": "49", + "opera": "36", + "edge": "14", + "firefox": "51", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + } +} diff --git a/node_modules/@babel/compat-data/data/plugins.json b/node_modules/@babel/compat-data/data/plugins.json new file mode 100644 index 0000000..7162a28 --- /dev/null +++ b/node_modules/@babel/compat-data/data/plugins.json @@ -0,0 +1,631 @@ +{ + "transform-class-static-block": { + "chrome": "94", + "opera": "80", + "edge": "94", + "firefox": "93", + "node": "16.11", + "electron": "15.0" + }, + "proposal-class-static-block": { + "chrome": "94", + "opera": "80", + "edge": "94", + "firefox": "93", + "node": "16.11", + "electron": "15.0" + }, + "transform-private-property-in-object": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "90", + "safari": "15", + "node": "16.9", + "ios": "15", + "electron": "13.0" + }, + "proposal-private-property-in-object": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "90", + "safari": "15", + "node": "16.9", + "ios": "15", + "electron": "13.0" + }, + "transform-class-properties": { + "chrome": "74", + "opera": "62", + "edge": "79", + "firefox": "90", + "safari": "14.1", + "node": "12", + "ios": "15", + "samsung": "11", + "electron": "6.0" + }, + "proposal-class-properties": { + "chrome": "74", + "opera": "62", + "edge": "79", + "firefox": "90", + "safari": "14.1", + "node": "12", + "ios": "15", + "samsung": "11", + "electron": "6.0" + }, + "transform-private-methods": { + "chrome": "84", + "opera": "70", + "edge": "84", + "firefox": "90", + "safari": "15", + "node": "14.6", + "ios": "15", + "samsung": "14", + "electron": "10.0" + }, + "proposal-private-methods": { + "chrome": "84", + "opera": "70", + "edge": "84", + "firefox": "90", + "safari": "15", + "node": "14.6", + "ios": "15", + "samsung": "14", + "electron": "10.0" + }, + "transform-numeric-separator": { + "chrome": "75", + "opera": "62", + "edge": "79", + "firefox": "70", + "safari": "13", + "node": "12.5", + "ios": "13", + "samsung": "11", + "rhino": "1.7.14", + "electron": "6.0" + }, + "proposal-numeric-separator": { + "chrome": "75", + "opera": "62", + "edge": "79", + "firefox": "70", + "safari": "13", + "node": "12.5", + "ios": "13", + "samsung": "11", + "rhino": "1.7.14", + "electron": "6.0" + }, + "transform-logical-assignment-operators": { + "chrome": "85", + "opera": "71", + "edge": "85", + "firefox": "79", + "safari": "14", + "node": "15", + "ios": "14", + "samsung": "14", + "electron": "10.0" + }, + "proposal-logical-assignment-operators": { + "chrome": "85", + "opera": "71", + "edge": "85", + "firefox": "79", + "safari": "14", + "node": "15", + "ios": "14", + "samsung": "14", + "electron": "10.0" + }, + "transform-nullish-coalescing-operator": { + "chrome": "80", + "opera": "67", + "edge": "80", + "firefox": "72", + "safari": "13.1", + "node": "14", + "ios": "13.4", + "samsung": "13", + "electron": "8.0" + }, + "proposal-nullish-coalescing-operator": { + "chrome": "80", + "opera": "67", + "edge": "80", + "firefox": "72", + "safari": "13.1", + "node": "14", + "ios": "13.4", + "samsung": "13", + "electron": "8.0" + }, + "transform-optional-chaining": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "74", + "safari": "13.1", + "node": "16.9", + "ios": "13.4", + "electron": "13.0" + }, + "proposal-optional-chaining": { + "chrome": "91", + "opera": "77", + "edge": "91", + "firefox": "74", + "safari": "13.1", + "node": "16.9", + "ios": "13.4", + "electron": "13.0" + }, + "transform-json-strings": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "62", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "9", + "rhino": "1.7.14", + "electron": "3.0" + }, + "proposal-json-strings": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "62", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "9", + "rhino": "1.7.14", + "electron": "3.0" + }, + "transform-optional-catch-binding": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "58", + "safari": "11.1", + "node": "10", + "ios": "11.3", + "samsung": "9", + "electron": "3.0" + }, + "proposal-optional-catch-binding": { + "chrome": "66", + "opera": "53", + "edge": "79", + "firefox": "58", + "safari": "11.1", + "node": "10", + "ios": "11.3", + "samsung": "9", + "electron": "3.0" + }, + "transform-parameters": { + "chrome": "49", + "opera": "36", + "edge": "18", + "firefox": "53", + "node": "6", + "samsung": "5", + "electron": "0.37" + }, + "transform-async-generator-functions": { + "chrome": "63", + "opera": "50", + "edge": "79", + "firefox": "57", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "8", + "electron": "3.0" + }, + "proposal-async-generator-functions": { + "chrome": "63", + "opera": "50", + "edge": "79", + "firefox": "57", + "safari": "12", + "node": "10", + "ios": "12", + "samsung": "8", + "electron": "3.0" + }, + "transform-object-rest-spread": { + "chrome": "60", + "opera": "47", + "edge": "79", + "firefox": "55", + "safari": "11.1", + "node": "8.3", + "ios": "11.3", + "samsung": "8", + "electron": "2.0" + }, + "proposal-object-rest-spread": { + "chrome": "60", + "opera": "47", + "edge": "79", + "firefox": "55", + "safari": "11.1", + "node": "8.3", + "ios": "11.3", + "samsung": "8", + "electron": "2.0" + }, + "transform-dotall-regex": { + "chrome": "62", + "opera": "49", + "edge": "79", + "firefox": "78", + "safari": "11.1", + "node": "8.10", + "ios": "11.3", + "samsung": "8", + "electron": "3.0" + }, + "transform-unicode-property-regex": { + "chrome": "64", + "opera": "51", + "edge": "79", + "firefox": "78", + "safari": "11.1", + "node": "10", + "ios": "11.3", + "samsung": "9", + "electron": "3.0" + }, + "proposal-unicode-property-regex": { + "chrome": "64", + "opera": "51", + "edge": "79", + "firefox": "78", + "safari": "11.1", + "node": "10", + "ios": "11.3", + "samsung": "9", + "electron": "3.0" + }, + "transform-named-capturing-groups-regex": { + "chrome": "64", + "opera": "51", + "edge": "79", + "firefox": "78", + "safari": "11.1", + "node": "10", + "ios": "11.3", + "samsung": "9", + "electron": "3.0" + }, + "transform-async-to-generator": { + "chrome": "55", + "opera": "42", + "edge": "15", + "firefox": "52", + "safari": "11", + "node": "7.6", + "ios": "11", + "samsung": "6", + "electron": "1.6" + }, + "transform-exponentiation-operator": { + "chrome": "52", + "opera": "39", + "edge": "14", + "firefox": "52", + "safari": "10.1", + "node": "7", + "ios": "10.3", + "samsung": "6", + "rhino": "1.7.14", + "electron": "1.3" + }, + "transform-template-literals": { + "chrome": "41", + "opera": "28", + "edge": "13", + "firefox": "34", + "safari": "13", + "node": "4", + "ios": "13", + "samsung": "3.4", + "electron": "0.21" + }, + "transform-literals": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "53", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "electron": "0.30" + }, + "transform-function-name": { + "chrome": "51", + "opera": "38", + "edge": "79", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "transform-arrow-functions": { + "chrome": "47", + "opera": "34", + "edge": "13", + "firefox": "43", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "rhino": "1.7.13", + "electron": "0.36" + }, + "transform-block-scoped-functions": { + "chrome": "41", + "opera": "28", + "edge": "12", + "firefox": "46", + "safari": "10", + "node": "4", + "ie": "11", + "ios": "10", + "samsung": "3.4", + "electron": "0.21" + }, + "transform-classes": { + "chrome": "46", + "opera": "33", + "edge": "13", + "firefox": "45", + "safari": "10", + "node": "5", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "transform-object-super": { + "chrome": "46", + "opera": "33", + "edge": "13", + "firefox": "45", + "safari": "10", + "node": "5", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "transform-shorthand-properties": { + "chrome": "43", + "opera": "30", + "edge": "12", + "firefox": "33", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "rhino": "1.7.14", + "electron": "0.27" + }, + "transform-duplicate-keys": { + "chrome": "42", + "opera": "29", + "edge": "12", + "firefox": "34", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "3.4", + "electron": "0.25" + }, + "transform-computed-properties": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "34", + "safari": "7.1", + "node": "4", + "ios": "8", + "samsung": "4", + "electron": "0.30" + }, + "transform-for-of": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "transform-sticky-regex": { + "chrome": "49", + "opera": "36", + "edge": "13", + "firefox": "3", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "0.37" + }, + "transform-unicode-escapes": { + "chrome": "44", + "opera": "31", + "edge": "12", + "firefox": "53", + "safari": "9", + "node": "4", + "ios": "9", + "samsung": "4", + "electron": "0.30" + }, + "transform-unicode-regex": { + "chrome": "50", + "opera": "37", + "edge": "13", + "firefox": "46", + "safari": "12", + "node": "6", + "ios": "12", + "samsung": "5", + "electron": "1.1" + }, + "transform-spread": { + "chrome": "46", + "opera": "33", + "edge": "13", + "firefox": "45", + "safari": "10", + "node": "5", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "transform-destructuring": { + "chrome": "51", + "opera": "38", + "edge": "15", + "firefox": "53", + "safari": "10", + "node": "6.5", + "ios": "10", + "samsung": "5", + "electron": "1.2" + }, + "transform-block-scoping": { + "chrome": "49", + "opera": "36", + "edge": "14", + "firefox": "51", + "safari": "11", + "node": "6", + "ios": "11", + "samsung": "5", + "electron": "0.37" + }, + "transform-typeof-symbol": { + "chrome": "38", + "opera": "25", + "edge": "12", + "firefox": "36", + "safari": "9", + "node": "0.12", + "ios": "9", + "samsung": "3", + "rhino": "1.7.13", + "electron": "0.20" + }, + "transform-new-target": { + "chrome": "46", + "opera": "33", + "edge": "14", + "firefox": "41", + "safari": "10", + "node": "5", + "ios": "10", + "samsung": "5", + "electron": "0.36" + }, + "transform-regenerator": { + "chrome": "50", + "opera": "37", + "edge": "13", + "firefox": "53", + "safari": "10", + "node": "6", + "ios": "10", + "samsung": "5", + "electron": "1.1" + }, + "transform-member-expression-literals": { + "chrome": "7", + "opera": "12", + "edge": "12", + "firefox": "2", + "safari": "5.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "transform-property-literals": { + "chrome": "7", + "opera": "12", + "edge": "12", + "firefox": "2", + "safari": "5.1", + "node": "0.4", + "ie": "9", + "android": "4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "transform-reserved-words": { + "chrome": "13", + "opera": "10.50", + "edge": "12", + "firefox": "2", + "safari": "3.1", + "node": "0.6", + "ie": "9", + "android": "4.4", + "ios": "6", + "phantom": "1.9", + "samsung": "1", + "rhino": "1.7.13", + "electron": "0.20" + }, + "transform-export-namespace-from": { + "chrome": "72", + "and_chr": "72", + "edge": "79", + "firefox": "80", + "and_ff": "80", + "node": "13.2", + "opera": "60", + "op_mob": "51", + "samsung": "11.0", + "android": "72", + "electron": "5.0" + }, + "proposal-export-namespace-from": { + "chrome": "72", + "and_chr": "72", + "edge": "79", + "firefox": "80", + "and_ff": "80", + "node": "13.2", + "opera": "60", + "op_mob": "51", + "samsung": "11.0", + "android": "72", + "electron": "5.0" + } +} diff --git a/node_modules/@babel/compat-data/native-modules.js b/node_modules/@babel/compat-data/native-modules.js new file mode 100644 index 0000000..8e97da4 --- /dev/null +++ b/node_modules/@babel/compat-data/native-modules.js @@ -0,0 +1 @@ +module.exports = require("./data/native-modules.json"); diff --git a/node_modules/@babel/compat-data/overlapping-plugins.js b/node_modules/@babel/compat-data/overlapping-plugins.js new file mode 100644 index 0000000..88242e4 --- /dev/null +++ b/node_modules/@babel/compat-data/overlapping-plugins.js @@ -0,0 +1 @@ +module.exports = require("./data/overlapping-plugins.json"); diff --git a/node_modules/@babel/compat-data/package.json b/node_modules/@babel/compat-data/package.json new file mode 100644 index 0000000..9201337 --- /dev/null +++ b/node_modules/@babel/compat-data/package.json @@ -0,0 +1,40 @@ +{ + "name": "@babel/compat-data", + "version": "7.19.4", + "author": "The Babel Team (https://babel.dev/team)", + "license": "MIT", + "description": "", + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-compat-data" + }, + "publishConfig": { + "access": "public" + }, + "exports": { + "./plugins": "./plugins.js", + "./native-modules": "./native-modules.js", + "./corejs2-built-ins": "./corejs2-built-ins.js", + "./corejs3-shipped-proposals": "./corejs3-shipped-proposals.js", + "./overlapping-plugins": "./overlapping-plugins.js", + "./plugin-bugfixes": "./plugin-bugfixes.js" + }, + "scripts": { + "build-data": "./scripts/download-compat-table.sh && node ./scripts/build-data.js && node ./scripts/build-modules-support.js && node ./scripts/build-bugfixes-targets.js" + }, + "keywords": [ + "babel", + "compat-table", + "compat-data" + ], + "devDependencies": { + "@mdn/browser-compat-data": "^4.0.10", + "core-js-compat": "^3.25.1", + "electron-to-chromium": "^1.4.248" + }, + "engines": { + "node": ">=6.9.0" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/compat-data/plugin-bugfixes.js b/node_modules/@babel/compat-data/plugin-bugfixes.js new file mode 100644 index 0000000..f390181 --- /dev/null +++ b/node_modules/@babel/compat-data/plugin-bugfixes.js @@ -0,0 +1 @@ +module.exports = require("./data/plugin-bugfixes.json"); diff --git a/node_modules/@babel/compat-data/plugins.js b/node_modules/@babel/compat-data/plugins.js new file mode 100644 index 0000000..42646ed --- /dev/null +++ b/node_modules/@babel/compat-data/plugins.js @@ -0,0 +1 @@ +module.exports = require("./data/plugins.json"); diff --git a/node_modules/@babel/core/LICENSE b/node_modules/@babel/core/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/core/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/core/README.md b/node_modules/@babel/core/README.md new file mode 100644 index 0000000..9b3a950 --- /dev/null +++ b/node_modules/@babel/core/README.md @@ -0,0 +1,19 @@ +# @babel/core + +> Babel compiler core. + +See our website [@babel/core](https://babeljs.io/docs/en/babel-core) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20core%22+is%3Aopen) associated with this package. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/core +``` + +or using yarn: + +```sh +yarn add @babel/core --dev +``` diff --git a/node_modules/@babel/core/cjs-proxy.cjs b/node_modules/@babel/core/cjs-proxy.cjs new file mode 100644 index 0000000..4bf8b5c --- /dev/null +++ b/node_modules/@babel/core/cjs-proxy.cjs @@ -0,0 +1,29 @@ +"use strict"; + +const babelP = import("./lib/index.js"); + +const functionNames = [ + "createConfigItem", + "loadPartialConfig", + "loadOptions", + "transform", + "transformFile", + "transformFromAst", + "parse", +]; + +for (const name of functionNames) { + exports[`${name}Sync`] = function () { + throw new Error( + `"${name}Sync" is not supported when loading @babel/core using require()` + ); + }; + exports[name] = function (...args) { + babelP.then(babel => { + babel[name](...args); + }); + }; + exports[`${name}Async`] = function (...args) { + return babelP.then(babel => babel[`${name}Async`](...args)); + }; +} diff --git a/node_modules/@babel/core/lib/config/cache-contexts.js b/node_modules/@babel/core/lib/config/cache-contexts.js new file mode 100644 index 0000000..d7c0912 --- /dev/null +++ b/node_modules/@babel/core/lib/config/cache-contexts.js @@ -0,0 +1,3 @@ +0 && 0; + +//# sourceMappingURL=cache-contexts.js.map diff --git a/node_modules/@babel/core/lib/config/cache-contexts.js.map b/node_modules/@babel/core/lib/config/cache-contexts.js.map new file mode 100644 index 0000000..37fb689 --- /dev/null +++ b/node_modules/@babel/core/lib/config/cache-contexts.js.map @@ -0,0 +1 @@ +{"version":3,"names":[],"sources":["../../src/config/cache-contexts.ts"],"sourcesContent":["import type { Targets } from \"@babel/helper-compilation-targets\";\n\nimport type { ConfigContext } from \"./config-chain\";\nimport type { CallerMetadata } from \"./validation/options\";\n\nexport type { ConfigContext as FullConfig };\n\nexport type FullPreset = {\n targets: Targets;\n} & ConfigContext;\nexport type FullPlugin = {\n assumptions: { [name: string]: boolean };\n} & FullPreset;\n\n// Context not including filename since it is used in places that cannot\n// process 'ignore'/'only' and other filename-based logic.\nexport type SimpleConfig = {\n envName: string;\n caller: CallerMetadata | undefined;\n};\nexport type SimplePreset = {\n targets: Targets;\n} & SimpleConfig;\nexport type SimplePlugin = {\n assumptions: {\n [name: string]: boolean;\n };\n} & SimplePreset;\n"],"mappings":""} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/caching.js b/node_modules/@babel/core/lib/config/caching.js new file mode 100644 index 0000000..31e7db1 --- /dev/null +++ b/node_modules/@babel/core/lib/config/caching.js @@ -0,0 +1,328 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assertSimpleType = assertSimpleType; +exports.makeStrongCache = makeStrongCache; +exports.makeStrongCacheSync = makeStrongCacheSync; +exports.makeWeakCache = makeWeakCache; +exports.makeWeakCacheSync = makeWeakCacheSync; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _async = require("../gensync-utils/async"); + +var _util = require("./util"); + +const synchronize = gen => { + return _gensync()(gen).sync; +}; + +function* genTrue() { + return true; +} + +function makeWeakCache(handler) { + return makeCachedFunction(WeakMap, handler); +} + +function makeWeakCacheSync(handler) { + return synchronize(makeWeakCache(handler)); +} + +function makeStrongCache(handler) { + return makeCachedFunction(Map, handler); +} + +function makeStrongCacheSync(handler) { + return synchronize(makeStrongCache(handler)); +} + +function makeCachedFunction(CallCache, handler) { + const callCacheSync = new CallCache(); + const callCacheAsync = new CallCache(); + const futureCache = new CallCache(); + return function* cachedFunction(arg, data) { + const asyncContext = yield* (0, _async.isAsync)(); + const callCache = asyncContext ? callCacheAsync : callCacheSync; + const cached = yield* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data); + if (cached.valid) return cached.value; + const cache = new CacheConfigurator(data); + const handlerResult = handler(arg, cache); + let finishLock; + let value; + + if ((0, _util.isIterableIterator)(handlerResult)) { + value = yield* (0, _async.onFirstPause)(handlerResult, () => { + finishLock = setupAsyncLocks(cache, futureCache, arg); + }); + } else { + value = handlerResult; + } + + updateFunctionCache(callCache, cache, arg, value); + + if (finishLock) { + futureCache.delete(arg); + finishLock.release(value); + } + + return value; + }; +} + +function* getCachedValue(cache, arg, data) { + const cachedValue = cache.get(arg); + + if (cachedValue) { + for (const { + value, + valid + } of cachedValue) { + if (yield* valid(data)) return { + valid: true, + value + }; + } + } + + return { + valid: false, + value: null + }; +} + +function* getCachedValueOrWait(asyncContext, callCache, futureCache, arg, data) { + const cached = yield* getCachedValue(callCache, arg, data); + + if (cached.valid) { + return cached; + } + + if (asyncContext) { + const cached = yield* getCachedValue(futureCache, arg, data); + + if (cached.valid) { + const value = yield* (0, _async.waitFor)(cached.value.promise); + return { + valid: true, + value + }; + } + } + + return { + valid: false, + value: null + }; +} + +function setupAsyncLocks(config, futureCache, arg) { + const finishLock = new Lock(); + updateFunctionCache(futureCache, config, arg, finishLock); + return finishLock; +} + +function updateFunctionCache(cache, config, arg, value) { + if (!config.configured()) config.forever(); + let cachedValue = cache.get(arg); + config.deactivate(); + + switch (config.mode()) { + case "forever": + cachedValue = [{ + value, + valid: genTrue + }]; + cache.set(arg, cachedValue); + break; + + case "invalidate": + cachedValue = [{ + value, + valid: config.validator() + }]; + cache.set(arg, cachedValue); + break; + + case "valid": + if (cachedValue) { + cachedValue.push({ + value, + valid: config.validator() + }); + } else { + cachedValue = [{ + value, + valid: config.validator() + }]; + cache.set(arg, cachedValue); + } + + } +} + +class CacheConfigurator { + constructor(data) { + this._active = true; + this._never = false; + this._forever = false; + this._invalidate = false; + this._configured = false; + this._pairs = []; + this._data = void 0; + this._data = data; + } + + simple() { + return makeSimpleConfigurator(this); + } + + mode() { + if (this._never) return "never"; + if (this._forever) return "forever"; + if (this._invalidate) return "invalidate"; + return "valid"; + } + + forever() { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + + if (this._never) { + throw new Error("Caching has already been configured with .never()"); + } + + this._forever = true; + this._configured = true; + } + + never() { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + + if (this._forever) { + throw new Error("Caching has already been configured with .forever()"); + } + + this._never = true; + this._configured = true; + } + + using(handler) { + if (!this._active) { + throw new Error("Cannot change caching after evaluation has completed."); + } + + if (this._never || this._forever) { + throw new Error("Caching has already been configured with .never or .forever()"); + } + + this._configured = true; + const key = handler(this._data); + const fn = (0, _async.maybeAsync)(handler, `You appear to be using an async cache handler, but Babel has been called synchronously`); + + if ((0, _async.isThenable)(key)) { + return key.then(key => { + this._pairs.push([key, fn]); + + return key; + }); + } + + this._pairs.push([key, fn]); + + return key; + } + + invalidate(handler) { + this._invalidate = true; + return this.using(handler); + } + + validator() { + const pairs = this._pairs; + return function* (data) { + for (const [key, fn] of pairs) { + if (key !== (yield* fn(data))) return false; + } + + return true; + }; + } + + deactivate() { + this._active = false; + } + + configured() { + return this._configured; + } + +} + +function makeSimpleConfigurator(cache) { + function cacheFn(val) { + if (typeof val === "boolean") { + if (val) cache.forever();else cache.never(); + return; + } + + return cache.using(() => assertSimpleType(val())); + } + + cacheFn.forever = () => cache.forever(); + + cacheFn.never = () => cache.never(); + + cacheFn.using = cb => cache.using(() => assertSimpleType(cb())); + + cacheFn.invalidate = cb => cache.invalidate(() => assertSimpleType(cb())); + + return cacheFn; +} + +function assertSimpleType(value) { + if ((0, _async.isThenable)(value)) { + throw new Error(`You appear to be using an async cache handler, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously handle your caching logic.`); + } + + if (value != null && typeof value !== "string" && typeof value !== "boolean" && typeof value !== "number") { + throw new Error("Cache keys must be either string, boolean, number, null, or undefined."); + } + + return value; +} + +class Lock { + constructor() { + this.released = false; + this.promise = void 0; + this._resolve = void 0; + this.promise = new Promise(resolve => { + this._resolve = resolve; + }); + } + + release(value) { + this.released = true; + + this._resolve(value); + } + +} + +0 && 0; + +//# sourceMappingURL=caching.js.map diff --git a/node_modules/@babel/core/lib/config/caching.js.map b/node_modules/@babel/core/lib/config/caching.js.map new file mode 100644 index 0000000..e5d3333 --- /dev/null +++ b/node_modules/@babel/core/lib/config/caching.js.map @@ -0,0 +1 @@ +{"version":3,"names":["synchronize","gen","gensync","sync","genTrue","makeWeakCache","handler","makeCachedFunction","WeakMap","makeWeakCacheSync","makeStrongCache","Map","makeStrongCacheSync","CallCache","callCacheSync","callCacheAsync","futureCache","cachedFunction","arg","data","asyncContext","isAsync","callCache","cached","getCachedValueOrWait","valid","value","cache","CacheConfigurator","handlerResult","finishLock","isIterableIterator","onFirstPause","setupAsyncLocks","updateFunctionCache","delete","release","getCachedValue","cachedValue","get","waitFor","promise","config","Lock","configured","forever","deactivate","mode","set","validator","push","constructor","_active","_never","_forever","_invalidate","_configured","_pairs","_data","simple","makeSimpleConfigurator","Error","never","using","key","fn","maybeAsync","isThenable","then","invalidate","pairs","cacheFn","val","assertSimpleType","cb","released","_resolve","Promise","resolve"],"sources":["../../src/config/caching.ts"],"sourcesContent":["import gensync from \"gensync\";\nimport type { Handler } from \"gensync\";\nimport {\n maybeAsync,\n isAsync,\n onFirstPause,\n waitFor,\n isThenable,\n} from \"../gensync-utils/async\";\nimport { isIterableIterator } from \"./util\";\n\nexport type { CacheConfigurator };\n\nexport type SimpleCacheConfigurator = {\n (forever: boolean): void;\n (handler: () => T): T;\n\n forever: () => void;\n never: () => void;\n using: (handler: () => T) => T;\n invalidate: (handler: () => T) => T;\n};\n\nexport type CacheEntry = Array<{\n value: ResultT;\n valid: (channel: SideChannel) => Handler;\n}>;\n\nconst synchronize = (\n gen: (...args: ArgsT) => Handler,\n): ((...args: ArgsT) => ResultT) => {\n return gensync(gen).sync;\n};\n\n// eslint-disable-next-line require-yield\nfunction* genTrue() {\n return true;\n}\n\nexport function makeWeakCache(\n handler: (\n arg: ArgT,\n cache: CacheConfigurator,\n ) => Handler | ResultT,\n): (arg: ArgT, data: SideChannel) => Handler {\n return makeCachedFunction(WeakMap, handler);\n}\n\nexport function makeWeakCacheSync(\n handler: (arg: ArgT, cache?: CacheConfigurator) => ResultT,\n): (arg: ArgT, data?: SideChannel) => ResultT {\n return synchronize<[ArgT, SideChannel], ResultT>(\n makeWeakCache(handler),\n );\n}\n\nexport function makeStrongCache(\n handler: (\n arg: ArgT,\n cache: CacheConfigurator,\n ) => Handler | ResultT,\n): (arg: ArgT, data: SideChannel) => Handler {\n return makeCachedFunction(Map, handler);\n}\n\nexport function makeStrongCacheSync(\n handler: (arg: ArgT, cache?: CacheConfigurator) => ResultT,\n): (arg: ArgT, data?: SideChannel) => ResultT {\n return synchronize<[ArgT, SideChannel], ResultT>(\n makeStrongCache(handler),\n );\n}\n\n/* NOTE: Part of the logic explained in this comment is explained in the\n * getCachedValueOrWait and setupAsyncLocks functions.\n *\n * > There are only two hard things in Computer Science: cache invalidation and naming things.\n * > -- Phil Karlton\n *\n * I don't know if Phil was also thinking about handling a cache whose invalidation function is\n * defined asynchronously is considered, but it is REALLY hard to do correctly.\n *\n * The implemented logic (only when gensync is run asynchronously) is the following:\n * 1. If there is a valid cache associated to the current \"arg\" parameter,\n * a. RETURN the cached value\n * 3. If there is a FinishLock associated to the current \"arg\" parameter representing a valid cache,\n * a. Wait for that lock to be released\n * b. RETURN the value associated with that lock\n * 5. Start executing the function to be cached\n * a. If it pauses on a promise, then\n * i. Let FinishLock be a new lock\n * ii. Store FinishLock as associated to the current \"arg\" parameter\n * iii. Wait for the function to finish executing\n * iv. Release FinishLock\n * v. Send the function result to anyone waiting on FinishLock\n * 6. Store the result in the cache\n * 7. RETURN the result\n */\nfunction makeCachedFunction(\n CallCache: new () => CacheMap,\n handler: (\n arg: ArgT,\n cache: CacheConfigurator,\n ) => Handler | ResultT,\n): (arg: ArgT, data: SideChannel) => Handler {\n const callCacheSync = new CallCache();\n const callCacheAsync = new CallCache();\n const futureCache = new CallCache>();\n\n return function* cachedFunction(arg: ArgT, data: SideChannel) {\n const asyncContext = yield* isAsync();\n const callCache = asyncContext ? callCacheAsync : callCacheSync;\n\n const cached = yield* getCachedValueOrWait(\n asyncContext,\n callCache,\n futureCache,\n arg,\n data,\n );\n if (cached.valid) return cached.value;\n\n const cache = new CacheConfigurator(data);\n\n const handlerResult: Handler | ResultT = handler(arg, cache);\n\n let finishLock: Lock;\n let value: ResultT;\n\n if (isIterableIterator(handlerResult)) {\n value = yield* onFirstPause(handlerResult, () => {\n finishLock = setupAsyncLocks(cache, futureCache, arg);\n });\n } else {\n value = handlerResult;\n }\n\n updateFunctionCache(callCache, cache, arg, value);\n\n if (finishLock) {\n futureCache.delete(arg);\n finishLock.release(value);\n }\n\n return value;\n };\n}\n\ntype CacheMap =\n | Map>\n // @ts-expect-error todo(flow->ts): add `extends object` constraint to ArgT\n | WeakMap>;\n\nfunction* getCachedValue(\n cache: CacheMap,\n arg: ArgT,\n data: SideChannel,\n): Handler<{ valid: true; value: ResultT } | { valid: false; value: null }> {\n const cachedValue: CacheEntry | void = cache.get(arg);\n\n if (cachedValue) {\n for (const { value, valid } of cachedValue) {\n if (yield* valid(data)) return { valid: true, value };\n }\n }\n\n return { valid: false, value: null };\n}\n\nfunction* getCachedValueOrWait(\n asyncContext: boolean,\n callCache: CacheMap,\n futureCache: CacheMap, SideChannel>,\n arg: ArgT,\n data: SideChannel,\n): Handler<{ valid: true; value: ResultT } | { valid: false; value: null }> {\n const cached = yield* getCachedValue(callCache, arg, data);\n if (cached.valid) {\n return cached;\n }\n\n if (asyncContext) {\n const cached = yield* getCachedValue(futureCache, arg, data);\n if (cached.valid) {\n const value = yield* waitFor(cached.value.promise);\n return { valid: true, value };\n }\n }\n\n return { valid: false, value: null };\n}\n\nfunction setupAsyncLocks(\n config: CacheConfigurator,\n futureCache: CacheMap, SideChannel>,\n arg: ArgT,\n): Lock {\n const finishLock = new Lock();\n\n updateFunctionCache(futureCache, config, arg, finishLock);\n\n return finishLock;\n}\n\nfunction updateFunctionCache<\n ArgT,\n ResultT,\n SideChannel,\n Cache extends CacheMap,\n>(\n cache: Cache,\n config: CacheConfigurator,\n arg: ArgT,\n value: ResultT,\n) {\n if (!config.configured()) config.forever();\n\n let cachedValue: CacheEntry | void = cache.get(arg);\n\n config.deactivate();\n\n switch (config.mode()) {\n case \"forever\":\n cachedValue = [{ value, valid: genTrue }];\n cache.set(arg, cachedValue);\n break;\n case \"invalidate\":\n cachedValue = [{ value, valid: config.validator() }];\n cache.set(arg, cachedValue);\n break;\n case \"valid\":\n if (cachedValue) {\n cachedValue.push({ value, valid: config.validator() });\n } else {\n cachedValue = [{ value, valid: config.validator() }];\n cache.set(arg, cachedValue);\n }\n }\n}\n\nclass CacheConfigurator {\n _active: boolean = true;\n _never: boolean = false;\n _forever: boolean = false;\n _invalidate: boolean = false;\n\n _configured: boolean = false;\n\n _pairs: Array<\n [cachedValue: unknown, handler: (data: SideChannel) => Handler]\n > = [];\n\n _data: SideChannel;\n\n constructor(data: SideChannel) {\n this._data = data;\n }\n\n simple() {\n return makeSimpleConfigurator(this);\n }\n\n mode() {\n if (this._never) return \"never\";\n if (this._forever) return \"forever\";\n if (this._invalidate) return \"invalidate\";\n return \"valid\";\n }\n\n forever() {\n if (!this._active) {\n throw new Error(\"Cannot change caching after evaluation has completed.\");\n }\n if (this._never) {\n throw new Error(\"Caching has already been configured with .never()\");\n }\n this._forever = true;\n this._configured = true;\n }\n\n never() {\n if (!this._active) {\n throw new Error(\"Cannot change caching after evaluation has completed.\");\n }\n if (this._forever) {\n throw new Error(\"Caching has already been configured with .forever()\");\n }\n this._never = true;\n this._configured = true;\n }\n\n using(handler: (data: SideChannel) => T): T {\n if (!this._active) {\n throw new Error(\"Cannot change caching after evaluation has completed.\");\n }\n if (this._never || this._forever) {\n throw new Error(\n \"Caching has already been configured with .never or .forever()\",\n );\n }\n this._configured = true;\n\n const key = handler(this._data);\n\n const fn = maybeAsync(\n handler,\n `You appear to be using an async cache handler, but Babel has been called synchronously`,\n );\n\n if (isThenable(key)) {\n // @ts-expect-error todo(flow->ts): improve function return type annotation\n return key.then((key: unknown) => {\n this._pairs.push([key, fn]);\n return key;\n });\n }\n\n this._pairs.push([key, fn]);\n return key;\n }\n\n invalidate(handler: (data: SideChannel) => T): T {\n this._invalidate = true;\n return this.using(handler);\n }\n\n validator(): (data: SideChannel) => Handler {\n const pairs = this._pairs;\n return function* (data: SideChannel) {\n for (const [key, fn] of pairs) {\n if (key !== (yield* fn(data))) return false;\n }\n return true;\n };\n }\n\n deactivate() {\n this._active = false;\n }\n\n configured() {\n return this._configured;\n }\n}\n\nfunction makeSimpleConfigurator(\n cache: CacheConfigurator,\n): SimpleCacheConfigurator {\n function cacheFn(val: any) {\n if (typeof val === \"boolean\") {\n if (val) cache.forever();\n else cache.never();\n return;\n }\n\n return cache.using(() => assertSimpleType(val()));\n }\n cacheFn.forever = () => cache.forever();\n cacheFn.never = () => cache.never();\n cacheFn.using = (cb: { (): SimpleType }) =>\n cache.using(() => assertSimpleType(cb()));\n cacheFn.invalidate = (cb: { (): SimpleType }) =>\n cache.invalidate(() => assertSimpleType(cb()));\n\n return cacheFn as any;\n}\n\n// Types are limited here so that in the future these values can be used\n// as part of Babel's caching logic.\nexport type SimpleType =\n | string\n | boolean\n | number\n | null\n | void\n | Promise;\nexport function assertSimpleType(value: unknown): SimpleType {\n if (isThenable(value)) {\n throw new Error(\n `You appear to be using an async cache handler, ` +\n `which your current version of Babel does not support. ` +\n `We may add support for this in the future, ` +\n `but if you're on the most recent version of @babel/core and still ` +\n `seeing this error, then you'll need to synchronously handle your caching logic.`,\n );\n }\n\n if (\n value != null &&\n typeof value !== \"string\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"number\"\n ) {\n throw new Error(\n \"Cache keys must be either string, boolean, number, null, or undefined.\",\n );\n }\n // @ts-expect-error Type 'unknown' is not assignable to type 'SimpleType'. This can be removed\n // when strictNullCheck is enabled\n return value;\n}\n\nclass Lock {\n released: boolean = false;\n promise: Promise;\n _resolve: (value: T) => void;\n\n constructor() {\n this.promise = new Promise(resolve => {\n this._resolve = resolve;\n });\n }\n\n release(value: T) {\n this.released = true;\n this._resolve(value);\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;;AAOA;;AAmBA,MAAMA,WAAW,GACfC,GADkB,IAEgB;EAClC,OAAOC,UAAA,CAAQD,GAAR,EAAaE,IAApB;AACD,CAJD;;AAOA,UAAUC,OAAV,GAAoB;EAClB,OAAO,IAAP;AACD;;AAEM,SAASC,aAAT,CACLC,OADK,EAK+C;EACpD,OAAOC,kBAAkB,CAA6BC,OAA7B,EAAsCF,OAAtC,CAAzB;AACD;;AAEM,SAASG,iBAAT,CACLH,OADK,EAEuC;EAC5C,OAAON,WAAW,CAChBK,aAAa,CAA6BC,OAA7B,CADG,CAAlB;AAGD;;AAEM,SAASI,eAA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,QAAL,GAAgB,IAAhB;;IACA,KAAKC,QAAL,CAAclD,KAAd;EACD;;AAdW"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/config-chain.js b/node_modules/@babel/core/lib/config/config-chain.js new file mode 100644 index 0000000..9f4d1d5 --- /dev/null +++ b/node_modules/@babel/core/lib/config/config-chain.js @@ -0,0 +1,572 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildPresetChain = buildPresetChain; +exports.buildPresetChainWalker = void 0; +exports.buildRootChain = buildRootChain; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _debug() { + const data = require("debug"); + + _debug = function () { + return data; + }; + + return data; +} + +var _options = require("./validation/options"); + +var _patternToRegex = require("./pattern-to-regex"); + +var _printer = require("./printer"); + +var _rewriteStackTrace = require("../errors/rewrite-stack-trace"); + +var _configError = require("../errors/config-error"); + +var _files = require("./files"); + +var _caching = require("./caching"); + +var _configDescriptors = require("./config-descriptors"); + +const debug = _debug()("babel:config:config-chain"); + +function* buildPresetChain(arg, context) { + const chain = yield* buildPresetChainWalker(arg, context); + if (!chain) return null; + return { + plugins: dedupDescriptors(chain.plugins), + presets: dedupDescriptors(chain.presets), + options: chain.options.map(o => normalizeOptions(o)), + files: new Set() + }; +} + +const buildPresetChainWalker = makeChainWalker({ + root: preset => loadPresetDescriptors(preset), + env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName), + overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index), + overridesEnv: (preset, index, envName) => loadPresetOverridesEnvDescriptors(preset)(index)(envName), + createLogger: () => () => {} +}); +exports.buildPresetChainWalker = buildPresetChainWalker; +const loadPresetDescriptors = (0, _caching.makeWeakCacheSync)(preset => buildRootDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors)); +const loadPresetEnvDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(envName => buildEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, envName))); +const loadPresetOverridesDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(index => buildOverrideDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index))); +const loadPresetOverridesEnvDescriptors = (0, _caching.makeWeakCacheSync)(preset => (0, _caching.makeStrongCacheSync)(index => (0, _caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(preset, preset.alias, _configDescriptors.createUncachedDescriptors, index, envName)))); + +function* buildRootChain(opts, context) { + let configReport, babelRcReport; + const programmaticLogger = new _printer.ConfigPrinter(); + const programmaticChain = yield* loadProgrammaticChain({ + options: opts, + dirname: context.cwd + }, context, undefined, programmaticLogger); + if (!programmaticChain) return null; + const programmaticReport = yield* programmaticLogger.output(); + let configFile; + + if (typeof opts.configFile === "string") { + configFile = yield* (0, _files.loadConfig)(opts.configFile, context.cwd, context.envName, context.caller); + } else if (opts.configFile !== false) { + configFile = yield* (0, _files.findRootConfig)(context.root, context.envName, context.caller); + } + + let { + babelrc, + babelrcRoots + } = opts; + let babelrcRootsDirectory = context.cwd; + const configFileChain = emptyChain(); + const configFileLogger = new _printer.ConfigPrinter(); + + if (configFile) { + const validatedFile = validateConfigFile(configFile); + const result = yield* loadFileChain(validatedFile, context, undefined, configFileLogger); + if (!result) return null; + configReport = yield* configFileLogger.output(); + + if (babelrc === undefined) { + babelrc = validatedFile.options.babelrc; + } + + if (babelrcRoots === undefined) { + babelrcRootsDirectory = validatedFile.dirname; + babelrcRoots = validatedFile.options.babelrcRoots; + } + + mergeChain(configFileChain, result); + } + + let ignoreFile, babelrcFile; + let isIgnored = false; + const fileChain = emptyChain(); + + if ((babelrc === true || babelrc === undefined) && typeof context.filename === "string") { + const pkgData = yield* (0, _files.findPackageData)(context.filename); + + if (pkgData && babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)) { + ({ + ignore: ignoreFile, + config: babelrcFile + } = yield* (0, _files.findRelativeConfig)(pkgData, context.envName, context.caller)); + + if (ignoreFile) { + fileChain.files.add(ignoreFile.filepath); + } + + if (ignoreFile && shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)) { + isIgnored = true; + } + + if (babelrcFile && !isIgnored) { + const validatedFile = validateBabelrcFile(babelrcFile); + const babelrcLogger = new _printer.ConfigPrinter(); + const result = yield* loadFileChain(validatedFile, context, undefined, babelrcLogger); + + if (!result) { + isIgnored = true; + } else { + babelRcReport = yield* babelrcLogger.output(); + mergeChain(fileChain, result); + } + } + + if (babelrcFile && isIgnored) { + fileChain.files.add(babelrcFile.filepath); + } + } + } + + if (context.showConfig) { + console.log(`Babel configs on "${context.filename}" (ascending priority):\n` + [configReport, babelRcReport, programmaticReport].filter(x => !!x).join("\n\n") + "\n-----End Babel configs-----"); + } + + const chain = mergeChain(mergeChain(mergeChain(emptyChain(), configFileChain), fileChain), programmaticChain); + return { + plugins: isIgnored ? [] : dedupDescriptors(chain.plugins), + presets: isIgnored ? [] : dedupDescriptors(chain.presets), + options: isIgnored ? [] : chain.options.map(o => normalizeOptions(o)), + fileHandling: isIgnored ? "ignored" : "transpile", + ignore: ignoreFile || undefined, + babelrc: babelrcFile || undefined, + config: configFile || undefined, + files: chain.files + }; +} + +function babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory) { + if (typeof babelrcRoots === "boolean") return babelrcRoots; + const absoluteRoot = context.root; + + if (babelrcRoots === undefined) { + return pkgData.directories.indexOf(absoluteRoot) !== -1; + } + + let babelrcPatterns = babelrcRoots; + + if (!Array.isArray(babelrcPatterns)) { + babelrcPatterns = [babelrcPatterns]; + } + + babelrcPatterns = babelrcPatterns.map(pat => { + return typeof pat === "string" ? _path().resolve(babelrcRootsDirectory, pat) : pat; + }); + + if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) { + return pkgData.directories.indexOf(absoluteRoot) !== -1; + } + + return babelrcPatterns.some(pat => { + if (typeof pat === "string") { + pat = (0, _patternToRegex.default)(pat, babelrcRootsDirectory); + } + + return pkgData.directories.some(directory => { + return matchPattern(pat, babelrcRootsDirectory, directory, context); + }); + }); +} + +const validateConfigFile = (0, _caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, _options.validate)("configfile", file.options, file.filepath) +})); +const validateBabelrcFile = (0, _caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, _options.validate)("babelrcfile", file.options, file.filepath) +})); +const validateExtendFile = (0, _caching.makeWeakCacheSync)(file => ({ + filepath: file.filepath, + dirname: file.dirname, + options: (0, _options.validate)("extendsfile", file.options, file.filepath) +})); +const loadProgrammaticChain = makeChainWalker({ + root: input => buildRootDescriptors(input, "base", _configDescriptors.createCachedDescriptors), + env: (input, envName) => buildEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, envName), + overrides: (input, index) => buildOverrideDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index), + overridesEnv: (input, index, envName) => buildOverrideEnvDescriptors(input, "base", _configDescriptors.createCachedDescriptors, index, envName), + createLogger: (input, context, baseLogger) => buildProgrammaticLogger(input, context, baseLogger) +}); +const loadFileChainWalker = makeChainWalker({ + root: file => loadFileDescriptors(file), + env: (file, envName) => loadFileEnvDescriptors(file)(envName), + overrides: (file, index) => loadFileOverridesDescriptors(file)(index), + overridesEnv: (file, index, envName) => loadFileOverridesEnvDescriptors(file)(index)(envName), + createLogger: (file, context, baseLogger) => buildFileLogger(file.filepath, context, baseLogger) +}); + +function* loadFileChain(input, context, files, baseLogger) { + const chain = yield* loadFileChainWalker(input, context, files, baseLogger); + + if (chain) { + chain.files.add(input.filepath); + } + + return chain; +} + +const loadFileDescriptors = (0, _caching.makeWeakCacheSync)(file => buildRootDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors)); +const loadFileEnvDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(envName => buildEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, envName))); +const loadFileOverridesDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(index => buildOverrideDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index))); +const loadFileOverridesEnvDescriptors = (0, _caching.makeWeakCacheSync)(file => (0, _caching.makeStrongCacheSync)(index => (0, _caching.makeStrongCacheSync)(envName => buildOverrideEnvDescriptors(file, file.filepath, _configDescriptors.createUncachedDescriptors, index, envName)))); + +function buildFileLogger(filepath, context, baseLogger) { + if (!baseLogger) { + return () => {}; + } + + return baseLogger.configure(context.showConfig, _printer.ChainFormatter.Config, { + filepath + }); +} + +function buildRootDescriptors({ + dirname, + options +}, alias, descriptors) { + return descriptors(dirname, options, alias); +} + +function buildProgrammaticLogger(_, context, baseLogger) { + var _context$caller; + + if (!baseLogger) { + return () => {}; + } + + return baseLogger.configure(context.showConfig, _printer.ChainFormatter.Programmatic, { + callerName: (_context$caller = context.caller) == null ? void 0 : _context$caller.name + }); +} + +function buildEnvDescriptors({ + dirname, + options +}, alias, descriptors, envName) { + const opts = options.env && options.env[envName]; + return opts ? descriptors(dirname, opts, `${alias}.env["${envName}"]`) : null; +} + +function buildOverrideDescriptors({ + dirname, + options +}, alias, descriptors, index) { + const opts = options.overrides && options.overrides[index]; + if (!opts) throw new Error("Assertion failure - missing override"); + return descriptors(dirname, opts, `${alias}.overrides[${index}]`); +} + +function buildOverrideEnvDescriptors({ + dirname, + options +}, alias, descriptors, index, envName) { + const override = options.overrides && options.overrides[index]; + if (!override) throw new Error("Assertion failure - missing override"); + const opts = override.env && override.env[envName]; + return opts ? descriptors(dirname, opts, `${alias}.overrides[${index}].env["${envName}"]`) : null; +} + +function makeChainWalker({ + root, + env, + overrides, + overridesEnv, + createLogger +}) { + return function* chainWalker(input, context, files = new Set(), baseLogger) { + const { + dirname + } = input; + const flattenedConfigs = []; + const rootOpts = root(input); + + if (configIsApplicable(rootOpts, dirname, context, input.filepath)) { + flattenedConfigs.push({ + config: rootOpts, + envName: undefined, + index: undefined + }); + const envOpts = env(input, context.envName); + + if (envOpts && configIsApplicable(envOpts, dirname, context, input.filepath)) { + flattenedConfigs.push({ + config: envOpts, + envName: context.envName, + index: undefined + }); + } + + (rootOpts.options.overrides || []).forEach((_, index) => { + const overrideOps = overrides(input, index); + + if (configIsApplicable(overrideOps, dirname, context, input.filepath)) { + flattenedConfigs.push({ + config: overrideOps, + index, + envName: undefined + }); + const overrideEnvOpts = overridesEnv(input, index, context.envName); + + if (overrideEnvOpts && configIsApplicable(overrideEnvOpts, dirname, context, input.filepath)) { + flattenedConfigs.push({ + config: overrideEnvOpts, + index, + envName: context.envName + }); + } + } + }); + } + + if (flattenedConfigs.some(({ + config: { + options: { + ignore, + only + } + } + }) => shouldIgnore(context, ignore, only, dirname))) { + return null; + } + + const chain = emptyChain(); + const logger = createLogger(input, context, baseLogger); + + for (const { + config, + index, + envName + } of flattenedConfigs) { + if (!(yield* mergeExtendsChain(chain, config.options, dirname, context, files, baseLogger))) { + return null; + } + + logger(config, index, envName); + yield* mergeChainOpts(chain, config); + } + + return chain; + }; +} + +function* mergeExtendsChain(chain, opts, dirname, context, files, baseLogger) { + if (opts.extends === undefined) return true; + const file = yield* (0, _files.loadConfig)(opts.extends, dirname, context.envName, context.caller); + + if (files.has(file)) { + throw new Error(`Configuration cycle detected loading ${file.filepath}.\n` + `File already loaded following the config chain:\n` + Array.from(files, file => ` - ${file.filepath}`).join("\n")); + } + + files.add(file); + const fileChain = yield* loadFileChain(validateExtendFile(file), context, files, baseLogger); + files.delete(file); + if (!fileChain) return false; + mergeChain(chain, fileChain); + return true; +} + +function mergeChain(target, source) { + target.options.push(...source.options); + target.plugins.push(...source.plugins); + target.presets.push(...source.presets); + + for (const file of source.files) { + target.files.add(file); + } + + return target; +} + +function* mergeChainOpts(target, { + options, + plugins, + presets +}) { + target.options.push(options); + target.plugins.push(...(yield* plugins())); + target.presets.push(...(yield* presets())); + return target; +} + +function emptyChain() { + return { + options: [], + presets: [], + plugins: [], + files: new Set() + }; +} + +function normalizeOptions(opts) { + const options = Object.assign({}, opts); + delete options.extends; + delete options.env; + delete options.overrides; + delete options.plugins; + delete options.presets; + delete options.passPerPreset; + delete options.ignore; + delete options.only; + delete options.test; + delete options.include; + delete options.exclude; + + if (Object.prototype.hasOwnProperty.call(options, "sourceMap")) { + options.sourceMaps = options.sourceMap; + delete options.sourceMap; + } + + return options; +} + +function dedupDescriptors(items) { + const map = new Map(); + const descriptors = []; + + for (const item of items) { + if (typeof item.value === "function") { + const fnKey = item.value; + let nameMap = map.get(fnKey); + + if (!nameMap) { + nameMap = new Map(); + map.set(fnKey, nameMap); + } + + let desc = nameMap.get(item.name); + + if (!desc) { + desc = { + value: item + }; + descriptors.push(desc); + if (!item.ownPass) nameMap.set(item.name, desc); + } else { + desc.value = item; + } + } else { + descriptors.push({ + value: item + }); + } + } + + return descriptors.reduce((acc, desc) => { + acc.push(desc.value); + return acc; + }, []); +} + +function configIsApplicable({ + options +}, dirname, context, configName) { + return (options.test === undefined || configFieldIsApplicable(context, options.test, dirname, configName)) && (options.include === undefined || configFieldIsApplicable(context, options.include, dirname, configName)) && (options.exclude === undefined || !configFieldIsApplicable(context, options.exclude, dirname, configName)); +} + +function configFieldIsApplicable(context, test, dirname, configName) { + const patterns = Array.isArray(test) ? test : [test]; + return matchesPatterns(context, patterns, dirname, configName); +} + +function ignoreListReplacer(_key, value) { + if (value instanceof RegExp) { + return String(value); + } + + return value; +} + +function shouldIgnore(context, ignore, only, dirname) { + if (ignore && matchesPatterns(context, ignore, dirname)) { + var _context$filename; + + const message = `No config is applied to "${(_context$filename = context.filename) != null ? _context$filename : "(unknown)"}" because it matches one of \`ignore: ${JSON.stringify(ignore, ignoreListReplacer)}\` from "${dirname}"`; + debug(message); + + if (context.showConfig) { + console.log(message); + } + + return true; + } + + if (only && !matchesPatterns(context, only, dirname)) { + var _context$filename2; + + const message = `No config is applied to "${(_context$filename2 = context.filename) != null ? _context$filename2 : "(unknown)"}" because it fails to match one of \`only: ${JSON.stringify(only, ignoreListReplacer)}\` from "${dirname}"`; + debug(message); + + if (context.showConfig) { + console.log(message); + } + + return true; + } + + return false; +} + +function matchesPatterns(context, patterns, dirname, configName) { + return patterns.some(pattern => matchPattern(pattern, dirname, context.filename, context, configName)); +} + +function matchPattern(pattern, dirname, pathToTest, context, configName) { + if (typeof pattern === "function") { + return !!(0, _rewriteStackTrace.endHiddenCallStack)(pattern)(pathToTest, { + dirname, + envName: context.envName, + caller: context.caller + }); + } + + if (typeof pathToTest !== "string") { + throw new _configError.default(`Configuration contains string/RegExp pattern, but no filename was passed to Babel`, configName); + } + + if (typeof pattern === "string") { + pattern = (0, _patternToRegex.default)(pattern, dirname); + } + + return pattern.test(pathToTest); +} + +0 && 0; + +//# sourceMappingURL=config-chain.js.map diff --git a/node_modules/@babel/core/lib/config/config-chain.js.map b/node_modules/@babel/core/lib/config/config-chain.js.map new file mode 100644 index 0000000..f211c7a --- /dev/null +++ b/node_modules/@babel/core/lib/config/config-chain.js.map @@ -0,0 +1 @@ +{"version":3,"names":["debug","buildDebug","buildPresetChain","arg","context","chain","buildPresetChainWalker","plugins","dedupDescriptors","presets","options","map","o","normalizeOptions","files","Set","makeChainWalker","root","preset","loadPresetDescriptors","env","envName","loadPresetEnvDescriptors","overrides","index","loadPresetOverridesDescriptors","overridesEnv","loadPresetOverridesEnvDescriptors","createLogger","makeWeakCacheSync","buildRootDescriptors","alias","createUncachedDescriptors","makeStrongCacheSync","buildEnvDescriptors","buildOverrideDescriptors","buildOverrideEnvDescriptors","buildRootChain","opts","configReport","babelRcReport","programmaticLogger","ConfigPrinter","programmaticChain","loadProgrammaticChain","dirname","cwd","undefined","programmaticReport","output","configFile","loadConfig","caller","findRootConfig","babelrc","babelrcRoots","babelrcRootsDirectory","configFileChain","emptyChain","configFileLogger","validatedFile","validateConfigFile","result","loadFileChain","mergeChain","ignoreFile","babelrcFile","isIgnored","fileChain","filename","pkgData","findPackageData","babelrcLoadEnabled","ignore","config","findRelativeConfig","add","filepath","shouldIgnore","validateBabelrcFile","babelrcLogger","showConfig","console","log","filter","x","join","fileHandling","absoluteRoot","directories","indexOf","babelrcPatterns","Array","isArray","pat","path","resolve","length","some","pathPatternToRegex","directory","matchPattern","file","validate","validateExtendFile","input","createCachedDescriptors","baseLogger","buildProgrammaticLogger","loadFileChainWalker","loadFileDescriptors","loadFileEnvDescriptors","loadFileOverridesDescriptors","loadFileOverridesEnvDescriptors","buildFileLogger","configure","ChainFormatter","Config","descriptors","_","Programmatic","callerName","name","Error","override","chainWalker","flattenedConfigs","rootOpts","configIsApplicable","push","envOpts","forEach","overrideOps","overrideEnvOpts","only","logger","mergeExtendsChain","mergeChainOpts","extends","has","from","delete","target","source","passPerPreset","test","include","exclude","Object","prototype","hasOwnProperty","call","sourceMaps","sourceMap","items","Map","item","value","fnKey","nameMap","get","set","desc","ownPass","reduce","acc","configName","configFieldIsApplicable","patterns","matchesPatterns","ignoreListReplacer","_key","RegExp","String","message","JSON","stringify","pattern","pathToTest","endHiddenCallStack","ConfigError"],"sources":["../../src/config/config-chain.ts"],"sourcesContent":["import path from \"path\";\nimport buildDebug from \"debug\";\nimport type { Handler } from \"gensync\";\nimport { validate } from \"./validation/options\";\nimport type {\n ValidatedOptions,\n IgnoreList,\n ConfigApplicableTest,\n BabelrcSearch,\n CallerMetadata,\n IgnoreItem,\n} from \"./validation/options\";\nimport pathPatternToRegex from \"./pattern-to-regex\";\nimport { ConfigPrinter, ChainFormatter } from \"./printer\";\nimport type { ReadonlyDeepArray } from \"./helpers/deep-array\";\n\nimport { endHiddenCallStack } from \"../errors/rewrite-stack-trace\";\nimport ConfigError from \"../errors/config-error\";\n\nconst debug = buildDebug(\"babel:config:config-chain\");\n\nimport {\n findPackageData,\n findRelativeConfig,\n findRootConfig,\n loadConfig,\n} from \"./files\";\nimport type { ConfigFile, IgnoreFile, FilePackageData } from \"./files\";\n\nimport { makeWeakCacheSync, makeStrongCacheSync } from \"./caching\";\n\nimport {\n createCachedDescriptors,\n createUncachedDescriptors,\n} from \"./config-descriptors\";\nimport type {\n UnloadedDescriptor,\n OptionsAndDescriptors,\n ValidatedFile,\n} from \"./config-descriptors\";\n\nexport type ConfigChain = {\n plugins: Array;\n presets: Array;\n options: Array;\n files: Set;\n};\n\nexport type PresetInstance = {\n options: ValidatedOptions;\n alias: string;\n dirname: string;\n externalDependencies: ReadonlyDeepArray;\n};\n\nexport type ConfigContext = {\n filename: string | undefined;\n cwd: string;\n root: string;\n envName: string;\n caller: CallerMetadata | undefined;\n showConfig: boolean;\n};\n\n/**\n * Build a config chain for a given preset.\n */\nexport function* buildPresetChain(\n arg: PresetInstance,\n context: any,\n): Handler {\n const chain = yield* buildPresetChainWalker(arg, context);\n if (!chain) return null;\n\n return {\n plugins: dedupDescriptors(chain.plugins),\n presets: dedupDescriptors(chain.presets),\n options: chain.options.map(o => normalizeOptions(o)),\n files: new Set(),\n };\n}\n\nexport const buildPresetChainWalker = makeChainWalker({\n root: preset => loadPresetDescriptors(preset),\n env: (preset, envName) => loadPresetEnvDescriptors(preset)(envName),\n overrides: (preset, index) => loadPresetOverridesDescriptors(preset)(index),\n overridesEnv: (preset, index, envName) =>\n loadPresetOverridesEnvDescriptors(preset)(index)(envName),\n createLogger: () => () => {}, // Currently we don't support logging how preset is expanded\n});\nconst loadPresetDescriptors = makeWeakCacheSync((preset: PresetInstance) =>\n buildRootDescriptors(preset, preset.alias, createUncachedDescriptors),\n);\nconst loadPresetEnvDescriptors = makeWeakCacheSync((preset: PresetInstance) =>\n makeStrongCacheSync((envName: string) =>\n buildEnvDescriptors(\n preset,\n preset.alias,\n createUncachedDescriptors,\n envName,\n ),\n ),\n);\nconst loadPresetOverridesDescriptors = makeWeakCacheSync(\n (preset: PresetInstance) =>\n makeStrongCacheSync((index: number) =>\n buildOverrideDescriptors(\n preset,\n preset.alias,\n createUncachedDescriptors,\n index,\n ),\n ),\n);\nconst loadPresetOverridesEnvDescriptors = makeWeakCacheSync(\n (preset: PresetInstance) =>\n makeStrongCacheSync((index: number) =>\n makeStrongCacheSync((envName: string) =>\n buildOverrideEnvDescriptors(\n preset,\n preset.alias,\n createUncachedDescriptors,\n index,\n envName,\n ),\n ),\n ),\n);\n\nexport type FileHandling = \"transpile\" | \"ignored\" | \"unsupported\";\nexport type RootConfigChain = ConfigChain & {\n babelrc: ConfigFile | void;\n config: ConfigFile | void;\n ignore: IgnoreFile | void;\n fileHandling: FileHandling;\n files: Set;\n};\n\n/**\n * Build a config chain for Babel's full root configuration.\n */\nexport function* buildRootChain(\n opts: ValidatedOptions,\n context: ConfigContext,\n): Handler {\n let configReport, babelRcReport;\n const programmaticLogger = new ConfigPrinter();\n const programmaticChain = yield* loadProgrammaticChain(\n {\n options: opts,\n dirname: context.cwd,\n },\n context,\n undefined,\n programmaticLogger,\n );\n if (!programmaticChain) return null;\n const programmaticReport = yield* programmaticLogger.output();\n\n let configFile;\n if (typeof opts.configFile === \"string\") {\n configFile = yield* loadConfig(\n opts.configFile,\n context.cwd,\n context.envName,\n context.caller,\n );\n } else if (opts.configFile !== false) {\n configFile = yield* findRootConfig(\n context.root,\n context.envName,\n context.caller,\n );\n }\n\n let { babelrc, babelrcRoots } = opts;\n let babelrcRootsDirectory = context.cwd;\n\n const configFileChain = emptyChain();\n const configFileLogger = new ConfigPrinter();\n if (configFile) {\n const validatedFile = validateConfigFile(configFile);\n const result = yield* loadFileChain(\n validatedFile,\n context,\n undefined,\n configFileLogger,\n );\n if (!result) return null;\n configReport = yield* configFileLogger.output();\n\n // Allow config files to toggle `.babelrc` resolution on and off and\n // specify where the roots are.\n if (babelrc === undefined) {\n babelrc = validatedFile.options.babelrc;\n }\n if (babelrcRoots === undefined) {\n babelrcRootsDirectory = validatedFile.dirname;\n babelrcRoots = validatedFile.options.babelrcRoots;\n }\n\n mergeChain(configFileChain, result);\n }\n\n let ignoreFile, babelrcFile;\n let isIgnored = false;\n const fileChain = emptyChain();\n // resolve all .babelrc files\n if (\n (babelrc === true || babelrc === undefined) &&\n typeof context.filename === \"string\"\n ) {\n const pkgData = yield* findPackageData(context.filename);\n\n if (\n pkgData &&\n babelrcLoadEnabled(context, pkgData, babelrcRoots, babelrcRootsDirectory)\n ) {\n ({ ignore: ignoreFile, config: babelrcFile } = yield* findRelativeConfig(\n pkgData,\n context.envName,\n context.caller,\n ));\n\n if (ignoreFile) {\n fileChain.files.add(ignoreFile.filepath);\n }\n\n if (\n ignoreFile &&\n shouldIgnore(context, ignoreFile.ignore, null, ignoreFile.dirname)\n ) {\n isIgnored = true;\n }\n\n if (babelrcFile && !isIgnored) {\n const validatedFile = validateBabelrcFile(babelrcFile);\n const babelrcLogger = new ConfigPrinter();\n const result = yield* loadFileChain(\n validatedFile,\n context,\n undefined,\n babelrcLogger,\n );\n if (!result) {\n isIgnored = true;\n } else {\n babelRcReport = yield* babelrcLogger.output();\n mergeChain(fileChain, result);\n }\n }\n\n if (babelrcFile && isIgnored) {\n fileChain.files.add(babelrcFile.filepath);\n }\n }\n }\n\n if (context.showConfig) {\n console.log(\n `Babel configs on \"${context.filename}\" (ascending priority):\\n` +\n // print config by the order of ascending priority\n [configReport, babelRcReport, programmaticReport]\n .filter(x => !!x)\n .join(\"\\n\\n\") +\n \"\\n-----End Babel configs-----\",\n );\n }\n // Insert file chain in front so programmatic options have priority\n // over configuration file chain items.\n const chain = mergeChain(\n mergeChain(mergeChain(emptyChain(), configFileChain), fileChain),\n programmaticChain,\n );\n\n return {\n plugins: isIgnored ? [] : dedupDescriptors(chain.plugins),\n presets: isIgnored ? [] : dedupDescriptors(chain.presets),\n options: isIgnored ? [] : chain.options.map(o => normalizeOptions(o)),\n fileHandling: isIgnored ? \"ignored\" : \"transpile\",\n ignore: ignoreFile || undefined,\n babelrc: babelrcFile || undefined,\n config: configFile || undefined,\n files: chain.files,\n };\n}\n\nfunction babelrcLoadEnabled(\n context: ConfigContext,\n pkgData: FilePackageData,\n babelrcRoots: BabelrcSearch | undefined,\n babelrcRootsDirectory: string,\n): boolean {\n if (typeof babelrcRoots === \"boolean\") return babelrcRoots;\n\n const absoluteRoot = context.root;\n\n // Fast path to avoid having to match patterns if the babelrc is just\n // loading in the standard root directory.\n if (babelrcRoots === undefined) {\n return pkgData.directories.indexOf(absoluteRoot) !== -1;\n }\n\n let babelrcPatterns = babelrcRoots;\n if (!Array.isArray(babelrcPatterns)) {\n babelrcPatterns = [babelrcPatterns as IgnoreItem];\n }\n babelrcPatterns = babelrcPatterns.map(pat => {\n return typeof pat === \"string\"\n ? path.resolve(babelrcRootsDirectory, pat)\n : pat;\n });\n\n // Fast path to avoid having to match patterns if the babelrc is just\n // loading in the standard root directory.\n if (babelrcPatterns.length === 1 && babelrcPatterns[0] === absoluteRoot) {\n return pkgData.directories.indexOf(absoluteRoot) !== -1;\n }\n\n return babelrcPatterns.some(pat => {\n if (typeof pat === \"string\") {\n pat = pathPatternToRegex(pat, babelrcRootsDirectory);\n }\n\n return pkgData.directories.some(directory => {\n return matchPattern(pat, babelrcRootsDirectory, directory, context);\n });\n });\n}\n\nconst validateConfigFile = makeWeakCacheSync(\n (file: ConfigFile): ValidatedFile => ({\n filepath: file.filepath,\n dirname: file.dirname,\n options: validate(\"configfile\", file.options, file.filepath),\n }),\n);\n\nconst validateBabelrcFile = makeWeakCacheSync(\n (file: ConfigFile): ValidatedFile => ({\n filepath: file.filepath,\n dirname: file.dirname,\n options: validate(\"babelrcfile\", file.options, file.filepath),\n }),\n);\n\nconst validateExtendFile = makeWeakCacheSync(\n (file: ConfigFile): ValidatedFile => ({\n filepath: file.filepath,\n dirname: file.dirname,\n options: validate(\"extendsfile\", file.options, file.filepath),\n }),\n);\n\n/**\n * Build a config chain for just the programmatic options passed into Babel.\n */\nconst loadProgrammaticChain = makeChainWalker({\n root: input => buildRootDescriptors(input, \"base\", createCachedDescriptors),\n env: (input, envName) =>\n buildEnvDescriptors(input, \"base\", createCachedDescriptors, envName),\n overrides: (input, index) =>\n buildOverrideDescriptors(input, \"base\", createCachedDescriptors, index),\n overridesEnv: (input, index, envName) =>\n buildOverrideEnvDescriptors(\n input,\n \"base\",\n createCachedDescriptors,\n index,\n envName,\n ),\n createLogger: (input, context, baseLogger) =>\n buildProgrammaticLogger(input, context, baseLogger),\n});\n\n/**\n * Build a config chain for a given file.\n */\nconst loadFileChainWalker = makeChainWalker({\n root: file => loadFileDescriptors(file),\n env: (file, envName) => loadFileEnvDescriptors(file)(envName),\n overrides: (file, index) => loadFileOverridesDescriptors(file)(index),\n overridesEnv: (file, index, envName) =>\n loadFileOverridesEnvDescriptors(file)(index)(envName),\n createLogger: (file, context, baseLogger) =>\n buildFileLogger(file.filepath, context, baseLogger),\n});\n\nfunction* loadFileChain(\n input: ValidatedFile,\n context: ConfigContext,\n files: Set,\n baseLogger: ConfigPrinter,\n) {\n const chain = yield* loadFileChainWalker(input, context, files, baseLogger);\n if (chain) {\n chain.files.add(input.filepath);\n }\n\n return chain;\n}\n\nconst loadFileDescriptors = makeWeakCacheSync((file: ValidatedFile) =>\n buildRootDescriptors(file, file.filepath, createUncachedDescriptors),\n);\nconst loadFileEnvDescriptors = makeWeakCacheSync((file: ValidatedFile) =>\n makeStrongCacheSync((envName: string) =>\n buildEnvDescriptors(\n file,\n file.filepath,\n createUncachedDescriptors,\n envName,\n ),\n ),\n);\nconst loadFileOverridesDescriptors = makeWeakCacheSync((file: ValidatedFile) =>\n makeStrongCacheSync((index: number) =>\n buildOverrideDescriptors(\n file,\n file.filepath,\n createUncachedDescriptors,\n index,\n ),\n ),\n);\nconst loadFileOverridesEnvDescriptors = makeWeakCacheSync(\n (file: ValidatedFile) =>\n makeStrongCacheSync((index: number) =>\n makeStrongCacheSync((envName: string) =>\n buildOverrideEnvDescriptors(\n file,\n file.filepath,\n createUncachedDescriptors,\n index,\n envName,\n ),\n ),\n ),\n);\n\nfunction buildFileLogger(\n filepath: string,\n context: ConfigContext,\n baseLogger: ConfigPrinter | void,\n) {\n if (!baseLogger) {\n return () => {};\n }\n return baseLogger.configure(context.showConfig, ChainFormatter.Config, {\n filepath,\n });\n}\n\nfunction buildRootDescriptors(\n { dirname, options }: Partial,\n alias: string,\n descriptors: (\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n) {\n return descriptors(dirname, options, alias);\n}\n\nfunction buildProgrammaticLogger(\n _: unknown,\n context: ConfigContext,\n baseLogger: ConfigPrinter | void,\n) {\n if (!baseLogger) {\n return () => {};\n }\n return baseLogger.configure(context.showConfig, ChainFormatter.Programmatic, {\n callerName: context.caller?.name,\n });\n}\n\nfunction buildEnvDescriptors(\n { dirname, options }: Partial,\n alias: string,\n descriptors: (\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n envName: string,\n) {\n const opts = options.env && options.env[envName];\n return opts ? descriptors(dirname, opts, `${alias}.env[\"${envName}\"]`) : null;\n}\n\nfunction buildOverrideDescriptors(\n { dirname, options }: Partial,\n alias: string,\n descriptors: (\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n index: number,\n) {\n const opts = options.overrides && options.overrides[index];\n if (!opts) throw new Error(\"Assertion failure - missing override\");\n\n return descriptors(dirname, opts, `${alias}.overrides[${index}]`);\n}\n\nfunction buildOverrideEnvDescriptors(\n { dirname, options }: Partial,\n alias: string,\n descriptors: (\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n ) => OptionsAndDescriptors,\n index: number,\n envName: string,\n) {\n const override = options.overrides && options.overrides[index];\n if (!override) throw new Error(\"Assertion failure - missing override\");\n\n const opts = override.env && override.env[envName];\n return opts\n ? descriptors(\n dirname,\n opts,\n `${alias}.overrides[${index}].env[\"${envName}\"]`,\n )\n : null;\n}\n\nfunction makeChainWalker<\n ArgT extends {\n options: ValidatedOptions;\n dirname: string;\n filepath?: string;\n },\n>({\n root,\n env,\n overrides,\n overridesEnv,\n createLogger,\n}: {\n root: (configEntry: ArgT) => OptionsAndDescriptors;\n env: (configEntry: ArgT, env: string) => OptionsAndDescriptors | null;\n overrides: (configEntry: ArgT, index: number) => OptionsAndDescriptors;\n overridesEnv: (\n configEntry: ArgT,\n index: number,\n env: string,\n ) => OptionsAndDescriptors | null;\n createLogger: (\n configEntry: ArgT,\n context: ConfigContext,\n printer: ConfigPrinter | void,\n ) => (\n opts: OptionsAndDescriptors,\n index?: number | null,\n env?: string | null,\n ) => void;\n}): (\n configEntry: ArgT,\n context: ConfigContext,\n files?: Set,\n baseLogger?: ConfigPrinter,\n) => Handler {\n return function* chainWalker(input, context, files = new Set(), baseLogger) {\n const { dirname } = input;\n\n const flattenedConfigs: Array<{\n config: OptionsAndDescriptors;\n index: number | undefined | null;\n envName: string | undefined | null;\n }> = [];\n\n const rootOpts = root(input);\n if (configIsApplicable(rootOpts, dirname, context, input.filepath)) {\n flattenedConfigs.push({\n config: rootOpts,\n envName: undefined,\n index: undefined,\n });\n\n const envOpts = env(input, context.envName);\n if (\n envOpts &&\n configIsApplicable(envOpts, dirname, context, input.filepath)\n ) {\n flattenedConfigs.push({\n config: envOpts,\n envName: context.envName,\n index: undefined,\n });\n }\n\n (rootOpts.options.overrides || []).forEach((_, index) => {\n const overrideOps = overrides(input, index);\n if (configIsApplicable(overrideOps, dirname, context, input.filepath)) {\n flattenedConfigs.push({\n config: overrideOps,\n index,\n envName: undefined,\n });\n\n const overrideEnvOpts = overridesEnv(input, index, context.envName);\n if (\n overrideEnvOpts &&\n configIsApplicable(\n overrideEnvOpts,\n dirname,\n context,\n input.filepath,\n )\n ) {\n flattenedConfigs.push({\n config: overrideEnvOpts,\n index,\n envName: context.envName,\n });\n }\n }\n });\n }\n\n // Process 'ignore' and 'only' before 'extends' items are processed so\n // that we don't do extra work loading extended configs if a file is\n // ignored.\n if (\n flattenedConfigs.some(\n ({\n config: {\n options: { ignore, only },\n },\n }) => shouldIgnore(context, ignore, only, dirname),\n )\n ) {\n return null;\n }\n\n const chain = emptyChain();\n const logger = createLogger(input, context, baseLogger);\n\n for (const { config, index, envName } of flattenedConfigs) {\n if (\n !(yield* mergeExtendsChain(\n chain,\n config.options,\n dirname,\n context,\n files,\n baseLogger,\n ))\n ) {\n return null;\n }\n\n logger(config, index, envName);\n yield* mergeChainOpts(chain, config);\n }\n return chain;\n };\n}\n\nfunction* mergeExtendsChain(\n chain: ConfigChain,\n opts: ValidatedOptions,\n dirname: string,\n context: ConfigContext,\n files: Set,\n baseLogger?: ConfigPrinter,\n): Handler {\n if (opts.extends === undefined) return true;\n\n const file = yield* loadConfig(\n opts.extends,\n dirname,\n context.envName,\n context.caller,\n );\n\n if (files.has(file)) {\n throw new Error(\n `Configuration cycle detected loading ${file.filepath}.\\n` +\n `File already loaded following the config chain:\\n` +\n Array.from(files, file => ` - ${file.filepath}`).join(\"\\n\"),\n );\n }\n\n files.add(file);\n const fileChain = yield* loadFileChain(\n validateExtendFile(file),\n context,\n files,\n baseLogger,\n );\n files.delete(file);\n\n if (!fileChain) return false;\n\n mergeChain(chain, fileChain);\n\n return true;\n}\n\nfunction mergeChain(target: ConfigChain, source: ConfigChain): ConfigChain {\n target.options.push(...source.options);\n target.plugins.push(...source.plugins);\n target.presets.push(...source.presets);\n for (const file of source.files) {\n target.files.add(file);\n }\n\n return target;\n}\n\nfunction* mergeChainOpts(\n target: ConfigChain,\n { options, plugins, presets }: OptionsAndDescriptors,\n): Handler {\n target.options.push(options);\n target.plugins.push(...(yield* plugins()));\n target.presets.push(...(yield* presets()));\n\n return target;\n}\n\nfunction emptyChain(): ConfigChain {\n return {\n options: [],\n presets: [],\n plugins: [],\n files: new Set(),\n };\n}\n\nfunction normalizeOptions(opts: ValidatedOptions): ValidatedOptions {\n const options = {\n ...opts,\n };\n delete options.extends;\n delete options.env;\n delete options.overrides;\n delete options.plugins;\n delete options.presets;\n delete options.passPerPreset;\n delete options.ignore;\n delete options.only;\n delete options.test;\n delete options.include;\n delete options.exclude;\n\n // \"sourceMap\" is just aliased to sourceMap, so copy it over as\n // we merge the options together.\n if (Object.prototype.hasOwnProperty.call(options, \"sourceMap\")) {\n options.sourceMaps = options.sourceMap;\n delete options.sourceMap;\n }\n return options;\n}\n\nfunction dedupDescriptors(\n items: Array,\n): Array {\n const map: Map<\n Function,\n Map\n > = new Map();\n\n const descriptors = [];\n\n for (const item of items) {\n if (typeof item.value === \"function\") {\n const fnKey = item.value;\n let nameMap = map.get(fnKey);\n if (!nameMap) {\n nameMap = new Map();\n map.set(fnKey, nameMap);\n }\n let desc = nameMap.get(item.name);\n if (!desc) {\n desc = { value: item };\n descriptors.push(desc);\n\n // Treat passPerPreset presets as unique, skipping them\n // in the merge processing steps.\n if (!item.ownPass) nameMap.set(item.name, desc);\n } else {\n desc.value = item;\n }\n } else {\n descriptors.push({ value: item });\n }\n }\n\n return descriptors.reduce((acc, desc) => {\n acc.push(desc.value);\n return acc;\n }, []);\n}\n\nfunction configIsApplicable(\n { options }: OptionsAndDescriptors,\n dirname: string,\n context: ConfigContext,\n configName: string,\n): boolean {\n return (\n (options.test === undefined ||\n configFieldIsApplicable(context, options.test, dirname, configName)) &&\n (options.include === undefined ||\n configFieldIsApplicable(context, options.include, dirname, configName)) &&\n (options.exclude === undefined ||\n !configFieldIsApplicable(context, options.exclude, dirname, configName))\n );\n}\n\nfunction configFieldIsApplicable(\n context: ConfigContext,\n test: ConfigApplicableTest,\n dirname: string,\n configName: string,\n): boolean {\n const patterns = Array.isArray(test) ? test : [test];\n\n return matchesPatterns(context, patterns, dirname, configName);\n}\n\n/**\n * Print the ignoreList-values in a more helpful way than the default.\n */\nfunction ignoreListReplacer(\n _key: string,\n value: IgnoreList | IgnoreItem,\n): IgnoreList | IgnoreItem | string {\n if (value instanceof RegExp) {\n return String(value);\n }\n\n return value;\n}\n\n/**\n * Tests if a filename should be ignored based on \"ignore\" and \"only\" options.\n */\nfunction shouldIgnore(\n context: ConfigContext,\n ignore: IgnoreList | undefined | null,\n only: IgnoreList | undefined | null,\n dirname: string,\n): boolean {\n if (ignore && matchesPatterns(context, ignore, dirname)) {\n const message = `No config is applied to \"${\n context.filename ?? \"(unknown)\"\n }\" because it matches one of \\`ignore: ${JSON.stringify(\n ignore,\n ignoreListReplacer,\n )}\\` from \"${dirname}\"`;\n debug(message);\n if (context.showConfig) {\n console.log(message);\n }\n return true;\n }\n\n if (only && !matchesPatterns(context, only, dirname)) {\n const message = `No config is applied to \"${\n context.filename ?? \"(unknown)\"\n }\" because it fails to match one of \\`only: ${JSON.stringify(\n only,\n ignoreListReplacer,\n )}\\` from \"${dirname}\"`;\n debug(message);\n if (context.showConfig) {\n console.log(message);\n }\n return true;\n }\n\n return false;\n}\n\n/**\n * Returns result of calling function with filename if pattern is a function.\n * Otherwise returns result of matching pattern Regex with filename.\n */\nfunction matchesPatterns(\n context: ConfigContext,\n patterns: IgnoreList,\n dirname: string,\n configName?: string,\n): boolean {\n return patterns.some(pattern =>\n matchPattern(pattern, dirname, context.filename, context, configName),\n );\n}\n\nfunction matchPattern(\n pattern: IgnoreItem,\n dirname: string,\n pathToTest: string | undefined,\n context: ConfigContext,\n configName?: string,\n): boolean {\n if (typeof pattern === \"function\") {\n return !!endHiddenCallStack(pattern)(pathToTest, {\n dirname,\n envName: context.envName,\n caller: context.caller,\n });\n }\n\n if (typeof pathToTest !== \"string\") {\n throw new ConfigError(\n `Configuration contains string/RegExp pattern, but no filename was passed to Babel`,\n configName,\n );\n }\n\n if (typeof pattern === \"string\") {\n pattern = pathPatternToRegex(pattern, dirname);\n }\n return pattern.test(pathToTest);\n}\n"],"mappings":";;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;;AASA;;AACA;;AAGA;;AACA;;AAIA;;AAQA;;AAEA;;AAZA,MAAMA,KAAK,GAAGC,QAAA,CAAW,2BAAX,CAAd;;AAgDO,UAAUC,gBAAV,CACLC,GADK,EAELC,OAFK,EAGwB;EAC7B,MAAMC,KAAK,GAAG,OAAOC,sBAAsB,CAACH,GAAD,EAAMC,OAAN,CAA3C;EACA,IAAI,CAACC,KAAL,EAAY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AAoC;IAClC,MAAM,IAAIE,oBAAJ,CACH,mFADG,EAEJd,UAFI,CAAN;EAID;;EAED,IAAI,OAAOW,OAAP,KAAmB,QAAvB,EAAiC;IAC/BA,OAAO,GAAG,IAAA9E,uBAAA,EAAmB8E,OAAnB,EAA4BpI,OAA5B,CAAV;EACD;;EACD,OAAOoI,OAAO,CAAChC,IAAR,CAAaiC,UAAb,CAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/config-descriptors.js b/node_modules/@babel/core/lib/config/config-descriptors.js new file mode 100644 index 0000000..cbadedd --- /dev/null +++ b/node_modules/@babel/core/lib/config/config-descriptors.js @@ -0,0 +1,233 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createCachedDescriptors = createCachedDescriptors; +exports.createDescriptor = createDescriptor; +exports.createUncachedDescriptors = createUncachedDescriptors; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _functional = require("../gensync-utils/functional"); + +var _files = require("./files"); + +var _item = require("./item"); + +var _caching = require("./caching"); + +var _resolveTargets = require("./resolve-targets"); + +function isEqualDescriptor(a, b) { + return a.name === b.name && a.value === b.value && a.options === b.options && a.dirname === b.dirname && a.alias === b.alias && a.ownPass === b.ownPass && (a.file && a.file.request) === (b.file && b.file.request) && (a.file && a.file.resolved) === (b.file && b.file.resolved); +} + +function* handlerOf(value) { + return value; +} + +function optionsWithResolvedBrowserslistConfigFile(options, dirname) { + if (typeof options.browserslistConfigFile === "string") { + options.browserslistConfigFile = (0, _resolveTargets.resolveBrowserslistConfigFile)(options.browserslistConfigFile, dirname); + } + + return options; +} + +function createCachedDescriptors(dirname, options, alias) { + const { + plugins, + presets, + passPerPreset + } = options; + return { + options: optionsWithResolvedBrowserslistConfigFile(options, dirname), + plugins: plugins ? () => createCachedPluginDescriptors(plugins, dirname)(alias) : () => handlerOf([]), + presets: presets ? () => createCachedPresetDescriptors(presets, dirname)(alias)(!!passPerPreset) : () => handlerOf([]) + }; +} + +function createUncachedDescriptors(dirname, options, alias) { + return { + options: optionsWithResolvedBrowserslistConfigFile(options, dirname), + plugins: (0, _functional.once)(() => createPluginDescriptors(options.plugins || [], dirname, alias)), + presets: (0, _functional.once)(() => createPresetDescriptors(options.presets || [], dirname, alias, !!options.passPerPreset)) + }; +} + +const PRESET_DESCRIPTOR_CACHE = new WeakMap(); +const createCachedPresetDescriptors = (0, _caching.makeWeakCacheSync)((items, cache) => { + const dirname = cache.using(dir => dir); + return (0, _caching.makeStrongCacheSync)(alias => (0, _caching.makeStrongCache)(function* (passPerPreset) { + const descriptors = yield* createPresetDescriptors(items, dirname, alias, passPerPreset); + return descriptors.map(desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc)); + })); +}); +const PLUGIN_DESCRIPTOR_CACHE = new WeakMap(); +const createCachedPluginDescriptors = (0, _caching.makeWeakCacheSync)((items, cache) => { + const dirname = cache.using(dir => dir); + return (0, _caching.makeStrongCache)(function* (alias) { + const descriptors = yield* createPluginDescriptors(items, dirname, alias); + return descriptors.map(desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc)); + }); +}); +const DEFAULT_OPTIONS = {}; + +function loadCachedDescriptor(cache, desc) { + const { + value, + options = DEFAULT_OPTIONS + } = desc; + if (options === false) return desc; + let cacheByOptions = cache.get(value); + + if (!cacheByOptions) { + cacheByOptions = new WeakMap(); + cache.set(value, cacheByOptions); + } + + let possibilities = cacheByOptions.get(options); + + if (!possibilities) { + possibilities = []; + cacheByOptions.set(options, possibilities); + } + + if (possibilities.indexOf(desc) === -1) { + const matches = possibilities.filter(possibility => isEqualDescriptor(possibility, desc)); + + if (matches.length > 0) { + return matches[0]; + } + + possibilities.push(desc); + } + + return desc; +} + +function* createPresetDescriptors(items, dirname, alias, passPerPreset) { + return yield* createDescriptors("preset", items, dirname, alias, passPerPreset); +} + +function* createPluginDescriptors(items, dirname, alias) { + return yield* createDescriptors("plugin", items, dirname, alias); +} + +function* createDescriptors(type, items, dirname, alias, ownPass) { + const descriptors = yield* _gensync().all(items.map((item, index) => createDescriptor(item, dirname, { + type, + alias: `${alias}$${index}`, + ownPass: !!ownPass + }))); + assertNoDuplicates(descriptors); + return descriptors; +} + +function* createDescriptor(pair, dirname, { + type, + alias, + ownPass +}) { + const desc = (0, _item.getItemDescriptor)(pair); + + if (desc) { + return desc; + } + + let name; + let options; + let value = pair; + + if (Array.isArray(value)) { + if (value.length === 3) { + [value, options, name] = value; + } else { + [value, options] = value; + } + } + + let file = undefined; + let filepath = null; + + if (typeof value === "string") { + if (typeof type !== "string") { + throw new Error("To resolve a string-based item, the type of item must be given"); + } + + const resolver = type === "plugin" ? _files.loadPlugin : _files.loadPreset; + const request = value; + ({ + filepath, + value + } = yield* resolver(value, dirname)); + file = { + request, + resolved: filepath + }; + } + + if (!value) { + throw new Error(`Unexpected falsy value: ${String(value)}`); + } + + if (typeof value === "object" && value.__esModule) { + if (value.default) { + value = value.default; + } else { + throw new Error("Must export a default export when using ES6 modules."); + } + } + + if (typeof value !== "object" && typeof value !== "function") { + throw new Error(`Unsupported format: ${typeof value}. Expected an object or a function.`); + } + + if (filepath !== null && typeof value === "object" && value) { + throw new Error(`Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`); + } + + return { + name, + alias: filepath || alias, + value, + options, + dirname, + ownPass, + file + }; +} + +function assertNoDuplicates(items) { + const map = new Map(); + + for (const item of items) { + if (typeof item.value !== "function") continue; + let nameMap = map.get(item.value); + + if (!nameMap) { + nameMap = new Set(); + map.set(item.value, nameMap); + } + + if (nameMap.has(item.name)) { + const conflicts = items.filter(i => i.value === item.value); + throw new Error([`Duplicate plugin/preset detected.`, `If you'd like to use two separate instances of a plugin,`, `they need separate names, e.g.`, ``, ` plugins: [`, ` ['some-plugin', {}],`, ` ['some-plugin', {}, 'some unique name'],`, ` ]`, ``, `Duplicates detected are:`, `${JSON.stringify(conflicts, null, 2)}`].join("\n")); + } + + nameMap.add(item.name); + } +} + +0 && 0; + +//# sourceMappingURL=config-descriptors.js.map diff --git a/node_modules/@babel/core/lib/config/config-descriptors.js.map b/node_modules/@babel/core/lib/config/config-descriptors.js.map new file mode 100644 index 0000000..37b2622 --- /dev/null +++ b/node_modules/@babel/core/lib/config/config-descriptors.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isEqualDescriptor","a","b","name","value","options","dirname","alias","ownPass","file","request","resolved","handlerOf","optionsWithResolvedBrowserslistConfigFile","browserslistConfigFile","resolveBrowserslistConfigFile","createCachedDescriptors","plugins","presets","passPerPreset","createCachedPluginDescriptors","createCachedPresetDescriptors","createUncachedDescriptors","once","createPluginDescriptors","createPresetDescriptors","PRESET_DESCRIPTOR_CACHE","WeakMap","makeWeakCacheSync","items","cache","using","dir","makeStrongCacheSync","makeStrongCache","descriptors","map","desc","loadCachedDescriptor","PLUGIN_DESCRIPTOR_CACHE","DEFAULT_OPTIONS","cacheByOptions","get","set","possibilities","indexOf","matches","filter","possibility","length","push","createDescriptors","type","gensync","all","item","index","createDescriptor","assertNoDuplicates","pair","getItemDescriptor","Array","isArray","undefined","filepath","Error","resolver","loadPlugin","loadPreset","String","__esModule","default","Map","nameMap","Set","has","conflicts","i","JSON","stringify","join","add"],"sources":["../../src/config/config-descriptors.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\nimport { once } from \"../gensync-utils/functional\";\n\nimport { loadPlugin, loadPreset } from \"./files\";\n\nimport { getItemDescriptor } from \"./item\";\n\nimport {\n makeWeakCacheSync,\n makeStrongCacheSync,\n makeStrongCache,\n} from \"./caching\";\nimport type { CacheConfigurator } from \"./caching\";\n\nimport type {\n ValidatedOptions,\n PluginList,\n PluginItem,\n} from \"./validation/options\";\n\nimport { resolveBrowserslistConfigFile } from \"./resolve-targets\";\n\n// Represents a config object and functions to lazily load the descriptors\n// for the plugins and presets so we don't load the plugins/presets unless\n// the options object actually ends up being applicable.\nexport type OptionsAndDescriptors = {\n options: ValidatedOptions;\n plugins: () => Handler>;\n presets: () => Handler>;\n};\n\n// Represents a plugin or presets at a given location in a config object.\n// At this point these have been resolved to a specific object or function,\n// but have not yet been executed to call functions with options.\nexport type UnloadedDescriptor = {\n name: string | undefined;\n value: any | Function;\n options: {} | undefined | false;\n dirname: string;\n alias: string;\n ownPass?: boolean;\n file?: {\n request: string;\n resolved: string;\n };\n};\n\nfunction isEqualDescriptor(\n a: UnloadedDescriptor,\n b: UnloadedDescriptor,\n): boolean {\n return (\n a.name === b.name &&\n a.value === b.value &&\n a.options === b.options &&\n a.dirname === b.dirname &&\n a.alias === b.alias &&\n a.ownPass === b.ownPass &&\n (a.file && a.file.request) === (b.file && b.file.request) &&\n (a.file && a.file.resolved) === (b.file && b.file.resolved)\n );\n}\n\nexport type ValidatedFile = {\n filepath: string;\n dirname: string;\n options: ValidatedOptions;\n};\n\n// eslint-disable-next-line require-yield\nfunction* handlerOf(value: T): Handler {\n return value;\n}\n\nfunction optionsWithResolvedBrowserslistConfigFile(\n options: ValidatedOptions,\n dirname: string,\n): ValidatedOptions {\n if (typeof options.browserslistConfigFile === \"string\") {\n options.browserslistConfigFile = resolveBrowserslistConfigFile(\n options.browserslistConfigFile,\n dirname,\n );\n }\n return options;\n}\n\n/**\n * Create a set of descriptors from a given options object, preserving\n * descriptor identity based on the identity of the plugin/preset arrays\n * themselves, and potentially on the identity of the plugins/presets + options.\n */\nexport function createCachedDescriptors(\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n): OptionsAndDescriptors {\n const { plugins, presets, passPerPreset } = options;\n return {\n options: optionsWithResolvedBrowserslistConfigFile(options, dirname),\n plugins: plugins\n ? () =>\n // @ts-expect-error todo(flow->ts) ts complains about incorrect arguments\n createCachedPluginDescriptors(plugins, dirname)(alias)\n : () => handlerOf([]),\n presets: presets\n ? () =>\n // @ts-expect-error todo(flow->ts) ts complains about incorrect arguments\n createCachedPresetDescriptors(presets, dirname)(alias)(\n !!passPerPreset,\n )\n : () => handlerOf([]),\n };\n}\n\n/**\n * Create a set of descriptors from a given options object, with consistent\n * identity for the descriptors, but not caching based on any specific identity.\n */\nexport function createUncachedDescriptors(\n dirname: string,\n options: ValidatedOptions,\n alias: string,\n): OptionsAndDescriptors {\n return {\n options: optionsWithResolvedBrowserslistConfigFile(options, dirname),\n // The returned result here is cached to represent a config object in\n // memory, so we build and memoize the descriptors to ensure the same\n // values are returned consistently.\n plugins: once(() =>\n createPluginDescriptors(options.plugins || [], dirname, alias),\n ),\n presets: once(() =>\n createPresetDescriptors(\n options.presets || [],\n dirname,\n alias,\n !!options.passPerPreset,\n ),\n ),\n };\n}\n\nconst PRESET_DESCRIPTOR_CACHE = new WeakMap();\nconst createCachedPresetDescriptors = makeWeakCacheSync(\n (items: PluginList, cache: CacheConfigurator) => {\n const dirname = cache.using(dir => dir);\n return makeStrongCacheSync((alias: string) =>\n makeStrongCache(function* (\n passPerPreset: boolean,\n ): Handler> {\n const descriptors = yield* createPresetDescriptors(\n items,\n dirname,\n alias,\n passPerPreset,\n );\n return descriptors.map(\n // Items are cached using the overall preset array identity when\n // possibly, but individual descriptors are also cached if a match\n // can be found in the previously-used descriptor lists.\n desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc),\n );\n }),\n );\n },\n);\n\nconst PLUGIN_DESCRIPTOR_CACHE = new WeakMap();\nconst createCachedPluginDescriptors = makeWeakCacheSync(\n (items: PluginList, cache: CacheConfigurator) => {\n const dirname = cache.using(dir => dir);\n return makeStrongCache(function* (\n alias: string,\n ): Handler> {\n const descriptors = yield* createPluginDescriptors(items, dirname, alias);\n return descriptors.map(\n // Items are cached using the overall plugin array identity when\n // possibly, but individual descriptors are also cached if a match\n // can be found in the previously-used descriptor lists.\n desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc),\n );\n });\n },\n);\n\n/**\n * When no options object is given in a descriptor, this object is used\n * as a WeakMap key in order to have consistent identity.\n */\nconst DEFAULT_OPTIONS = {};\n\n/**\n * Given the cache and a descriptor, returns a matching descriptor from the\n * cache, or else returns the input descriptor and adds it to the cache for\n * next time.\n */\nfunction loadCachedDescriptor(\n cache: WeakMap<{} | Function, WeakMap<{}, Array>>,\n desc: UnloadedDescriptor,\n) {\n const { value, options = DEFAULT_OPTIONS } = desc;\n if (options === false) return desc;\n\n let cacheByOptions = cache.get(value);\n if (!cacheByOptions) {\n cacheByOptions = new WeakMap();\n cache.set(value, cacheByOptions);\n }\n\n let possibilities = cacheByOptions.get(options);\n if (!possibilities) {\n possibilities = [];\n cacheByOptions.set(options, possibilities);\n }\n\n if (possibilities.indexOf(desc) === -1) {\n const matches = possibilities.filter(possibility =>\n isEqualDescriptor(possibility, desc),\n );\n if (matches.length > 0) {\n return matches[0];\n }\n\n possibilities.push(desc);\n }\n\n return desc;\n}\n\nfunction* createPresetDescriptors(\n items: PluginList,\n dirname: string,\n alias: string,\n passPerPreset: boolean,\n): Handler> {\n return yield* createDescriptors(\n \"preset\",\n items,\n dirname,\n alias,\n passPerPreset,\n );\n}\n\nfunction* createPluginDescriptors(\n items: PluginList,\n dirname: string,\n alias: string,\n): Handler> {\n return yield* createDescriptors(\"plugin\", items, dirname, alias);\n}\n\nfunction* createDescriptors(\n type: \"plugin\" | \"preset\",\n items: PluginList,\n dirname: string,\n alias: string,\n ownPass?: boolean,\n): Handler> {\n const descriptors = yield* gensync.all(\n items.map((item, index) =>\n createDescriptor(item, dirname, {\n type,\n alias: `${alias}$${index}`,\n ownPass: !!ownPass,\n }),\n ),\n );\n\n assertNoDuplicates(descriptors);\n\n return descriptors;\n}\n\n/**\n * Given a plugin/preset item, resolve it into a standard format.\n */\nexport function* createDescriptor(\n pair: PluginItem,\n dirname: string,\n {\n type,\n alias,\n ownPass,\n }: {\n type?: \"plugin\" | \"preset\";\n alias: string;\n ownPass?: boolean;\n },\n): Handler {\n const desc = getItemDescriptor(pair);\n if (desc) {\n return desc;\n }\n\n let name;\n let options;\n // todo(flow->ts) better type annotation\n let value: any = pair;\n if (Array.isArray(value)) {\n if (value.length === 3) {\n [value, options, name] = value;\n } else {\n [value, options] = value;\n }\n }\n\n let file = undefined;\n let filepath = null;\n if (typeof value === \"string\") {\n if (typeof type !== \"string\") {\n throw new Error(\n \"To resolve a string-based item, the type of item must be given\",\n );\n }\n const resolver = type === \"plugin\" ? loadPlugin : loadPreset;\n const request = value;\n\n ({ filepath, value } = yield* resolver(value, dirname));\n\n file = {\n request,\n resolved: filepath,\n };\n }\n\n if (!value) {\n throw new Error(`Unexpected falsy value: ${String(value)}`);\n }\n\n if (typeof value === \"object\" && value.__esModule) {\n if (value.default) {\n value = value.default;\n } else {\n throw new Error(\"Must export a default export when using ES6 modules.\");\n }\n }\n\n if (typeof value !== \"object\" && typeof value !== \"function\") {\n throw new Error(\n `Unsupported format: ${typeof value}. Expected an object or a function.`,\n );\n }\n\n if (filepath !== null && typeof value === \"object\" && value) {\n // We allow object values for plugins/presets nested directly within a\n // config object, because it can be useful to define them in nested\n // configuration contexts.\n throw new Error(\n `Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`,\n );\n }\n\n return {\n name,\n alias: filepath || alias,\n value,\n options,\n dirname,\n ownPass,\n file,\n };\n}\n\nfunction assertNoDuplicates(items: Array): void {\n const map = new Map();\n\n for (const item of items) {\n if (typeof item.value !== \"function\") continue;\n\n let nameMap = map.get(item.value);\n if (!nameMap) {\n nameMap = new Set();\n map.set(item.value, nameMap);\n }\n\n if (nameMap.has(item.name)) {\n const conflicts = items.filter(i => i.value === item.value);\n throw new Error(\n [\n `Duplicate plugin/preset detected.`,\n `If you'd like to use two separate instances of a plugin,`,\n `they need separate names, e.g.`,\n ``,\n ` plugins: [`,\n ` ['some-plugin', {}],`,\n ` ['some-plugin', {}, 'some unique name'],`,\n ` ]`,\n ``,\n `Duplicates detected are:`,\n `${JSON.stringify(conflicts, null, 2)}`,\n ].join(\"\\n\"),\n );\n }\n\n nameMap.add(item.name);\n }\n}\n"],"mappings":";;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;;AAEA;;AAEA;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,EATH,EAUG,0BAVH,EAWG,GAAEa,IAAI,CAACC,SAAL,CAAeH,SAAf,EAA0B,IAA1B,EAAgC,CAAhC,CAAmC,EAXxC,EAYEI,IAZF,CAYO,IAZP,CADI,CAAN;IAeD;;IAEDP,OAAO,CAACQ,GAAR,CAAY1B,IAAI,CAACpD,IAAjB;EACD;AACF"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/configuration.js b/node_modules/@babel/core/lib/config/files/configuration.js new file mode 100644 index 0000000..27d4f0e --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/configuration.js @@ -0,0 +1,362 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ROOT_CONFIG_FILENAMES = void 0; +exports.findConfigUpwards = findConfigUpwards; +exports.findRelativeConfig = findRelativeConfig; +exports.findRootConfig = findRootConfig; +exports.loadConfig = loadConfig; +exports.resolveShowConfigPath = resolveShowConfigPath; + +function _debug() { + const data = require("debug"); + + _debug = function () { + return data; + }; + + return data; +} + +function _fs() { + const data = require("fs"); + + _fs = function () { + return data; + }; + + return data; +} + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _json() { + const data = require("json5"); + + _json = function () { + return data; + }; + + return data; +} + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _caching = require("../caching"); + +var _configApi = require("../helpers/config-api"); + +var _utils = require("./utils"); + +var _moduleTypes = require("./module-types"); + +var _patternToRegex = require("../pattern-to-regex"); + +var _configError = require("../../errors/config-error"); + +var fs = require("../../gensync-utils/fs"); + +function _module() { + const data = require("module"); + + _module = function () { + return data; + }; + + return data; +} + +var _rewriteStackTrace = require("../../errors/rewrite-stack-trace"); + +const debug = _debug()("babel:config:loading:files:configuration"); + +const ROOT_CONFIG_FILENAMES = ["babel.config.js", "babel.config.cjs", "babel.config.mjs", "babel.config.json"]; +exports.ROOT_CONFIG_FILENAMES = ROOT_CONFIG_FILENAMES; +const RELATIVE_CONFIG_FILENAMES = [".babelrc", ".babelrc.js", ".babelrc.cjs", ".babelrc.mjs", ".babelrc.json"]; +const BABELIGNORE_FILENAME = ".babelignore"; + +function findConfigUpwards(rootDir) { + let dirname = rootDir; + + for (;;) { + for (const filename of ROOT_CONFIG_FILENAMES) { + if (_fs().existsSync(_path().join(dirname, filename))) { + return dirname; + } + } + + const nextDir = _path().dirname(dirname); + + if (dirname === nextDir) break; + dirname = nextDir; + } + + return null; +} + +function* findRelativeConfig(packageData, envName, caller) { + let config = null; + let ignore = null; + + const dirname = _path().dirname(packageData.filepath); + + for (const loc of packageData.directories) { + if (!config) { + var _packageData$pkg; + + config = yield* loadOneConfig(RELATIVE_CONFIG_FILENAMES, loc, envName, caller, ((_packageData$pkg = packageData.pkg) == null ? void 0 : _packageData$pkg.dirname) === loc ? packageToBabelConfig(packageData.pkg) : null); + } + + if (!ignore) { + const ignoreLoc = _path().join(loc, BABELIGNORE_FILENAME); + + ignore = yield* readIgnoreConfig(ignoreLoc); + + if (ignore) { + debug("Found ignore %o from %o.", ignore.filepath, dirname); + } + } + } + + return { + config, + ignore + }; +} + +function findRootConfig(dirname, envName, caller) { + return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller); +} + +function* loadOneConfig(names, dirname, envName, caller, previousConfig = null) { + const configs = yield* _gensync().all(names.map(filename => readConfig(_path().join(dirname, filename), envName, caller))); + const config = configs.reduce((previousConfig, config) => { + if (config && previousConfig) { + throw new _configError.default(`Multiple configuration files found. Please remove one:\n` + ` - ${_path().basename(previousConfig.filepath)}\n` + ` - ${config.filepath}\n` + `from ${dirname}`); + } + + return config || previousConfig; + }, previousConfig); + + if (config) { + debug("Found configuration %o from %o.", config.filepath, dirname); + } + + return config; +} + +function* loadConfig(name, dirname, envName, caller) { + const filepath = (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, { + paths: [b] + }, M = require("module")) => { + let f = M._findPath(r, M._nodeModulePaths(b).concat(b)); + + if (f) return f; + f = new Error(`Cannot resolve module '${r}'`); + f.code = "MODULE_NOT_FOUND"; + throw f; + })(name, { + paths: [dirname] + }); + const conf = yield* readConfig(filepath, envName, caller); + + if (!conf) { + throw new _configError.default(`Config file contains no configuration data`, filepath); + } + + debug("Loaded config %o from %o.", name, dirname); + return conf; +} + +function readConfig(filepath, envName, caller) { + const ext = _path().extname(filepath); + + return ext === ".js" || ext === ".cjs" || ext === ".mjs" ? readConfigJS(filepath, { + envName, + caller + }) : readConfigJSON5(filepath); +} + +const LOADING_CONFIGS = new Set(); +const readConfigJS = (0, _caching.makeStrongCache)(function* readConfigJS(filepath, cache) { + if (!_fs().existsSync(filepath)) { + cache.never(); + return null; + } + + if (LOADING_CONFIGS.has(filepath)) { + cache.never(); + debug("Auto-ignoring usage of config %o.", filepath); + return { + filepath, + dirname: _path().dirname(filepath), + options: {} + }; + } + + let options; + + try { + LOADING_CONFIGS.add(filepath); + options = yield* (0, _moduleTypes.default)(filepath, "You appear to be using a native ECMAScript module configuration " + "file, which is only supported when running Babel asynchronously."); + } finally { + LOADING_CONFIGS.delete(filepath); + } + + let assertCache = false; + + if (typeof options === "function") { + yield* []; + options = (0, _rewriteStackTrace.endHiddenCallStack)(options)((0, _configApi.makeConfigAPI)(cache)); + assertCache = true; + } + + if (!options || typeof options !== "object" || Array.isArray(options)) { + throw new _configError.default(`Configuration should be an exported JavaScript object.`, filepath); + } + + if (typeof options.then === "function") { + throw new _configError.default(`You appear to be using an async configuration, ` + `which your current version of Babel does not support. ` + `We may add support for this in the future, ` + `but if you're on the most recent version of @babel/core and still ` + `seeing this error, then you'll need to synchronously return your config.`, filepath); + } + + if (assertCache && !cache.configured()) throwConfigError(filepath); + return { + filepath, + dirname: _path().dirname(filepath), + options + }; +}); +const packageToBabelConfig = (0, _caching.makeWeakCacheSync)(file => { + const babel = file.options["babel"]; + if (typeof babel === "undefined") return null; + + if (typeof babel !== "object" || Array.isArray(babel) || babel === null) { + throw new _configError.default(`.babel property must be an object`, file.filepath); + } + + return { + filepath: file.filepath, + dirname: file.dirname, + options: babel + }; +}); +const readConfigJSON5 = (0, _utils.makeStaticFileCache)((filepath, content) => { + let options; + + try { + options = _json().parse(content); + } catch (err) { + throw new _configError.default(`Error while parsing config - ${err.message}`, filepath); + } + + if (!options) throw new _configError.default(`No config detected`, filepath); + + if (typeof options !== "object") { + throw new _configError.default(`Config returned typeof ${typeof options}`, filepath); + } + + if (Array.isArray(options)) { + throw new _configError.default(`Expected config object but found array`, filepath); + } + + delete options["$schema"]; + return { + filepath, + dirname: _path().dirname(filepath), + options + }; +}); +const readIgnoreConfig = (0, _utils.makeStaticFileCache)((filepath, content) => { + const ignoreDir = _path().dirname(filepath); + + const ignorePatterns = content.split("\n").map(line => line.replace(/#(.*?)$/, "").trim()).filter(line => !!line); + + for (const pattern of ignorePatterns) { + if (pattern[0] === "!") { + throw new _configError.default(`Negation of file paths is not supported.`, filepath); + } + } + + return { + filepath, + dirname: _path().dirname(filepath), + ignore: ignorePatterns.map(pattern => (0, _patternToRegex.default)(pattern, ignoreDir)) + }; +}); + +function* resolveShowConfigPath(dirname) { + const targetPath = process.env.BABEL_SHOW_CONFIG_FOR; + + if (targetPath != null) { + const absolutePath = _path().resolve(dirname, targetPath); + + const stats = yield* fs.stat(absolutePath); + + if (!stats.isFile()) { + throw new Error(`${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`); + } + + return absolutePath; + } + + return null; +} + +function throwConfigError(filepath) { + throw new _configError.default(`\ +Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured +for various types of caching, using the first param of their handler functions: + +module.exports = function(api) { + // The API exposes the following: + + // Cache the returned value forever and don't call this function again. + api.cache(true); + + // Don't cache at all. Not recommended because it will be very slow. + api.cache(false); + + // Cached based on the value of some function. If this function returns a value different from + // a previously-encountered value, the plugins will re-evaluate. + var env = api.cache(() => process.env.NODE_ENV); + + // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for + // any possible NODE_ENV value that might come up during plugin execution. + var isProd = api.cache(() => process.env.NODE_ENV === "production"); + + // .cache(fn) will perform a linear search though instances to find the matching plugin based + // based on previous instantiated plugins. If you want to recreate the plugin and discard the + // previous instance whenever something changes, you may use: + var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production"); + + // Note, we also expose the following more-verbose versions of the above examples: + api.cache.forever(); // api.cache(true) + api.cache.never(); // api.cache(false) + api.cache.using(fn); // api.cache(fn) + + // Return the value that will be cached. + return { }; +};`, filepath); +} + +0 && 0; + +//# sourceMappingURL=configuration.js.map diff --git a/node_modules/@babel/core/lib/config/files/configuration.js.map b/node_modules/@babel/core/lib/config/files/configuration.js.map new file mode 100644 index 0000000..c237d12 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/configuration.js.map @@ -0,0 +1 @@ +{"version":3,"names":["debug","buildDebug","ROOT_CONFIG_FILENAMES","RELATIVE_CONFIG_FILENAMES","BABELIGNORE_FILENAME","findConfigUpwards","rootDir","dirname","filename","nodeFs","existsSync","path","join","nextDir","findRelativeConfig","packageData","envName","caller","config","ignore","filepath","loc","directories","loadOneConfig","pkg","packageToBabelConfig","ignoreLoc","readIgnoreConfig","findRootConfig","names","previousConfig","configs","gensync","all","map","readConfig","reduce","ConfigError","basename","loadConfig","name","paths","conf","ext","extname","readConfigJS","readConfigJSON5","LOADING_CONFIGS","Set","makeStrongCache","cache","never","has","options","add","loadCjsOrMjsDefault","delete","assertCache","endHiddenCallStack","makeConfigAPI","Array","isArray","then","configured","throwConfigError","makeWeakCacheSync","file","babel","makeStaticFileCache","content","json5","parse","err","message","ignoreDir","ignorePatterns","split","line","replace","trim","filter","pattern","pathPatternToRegex","resolveShowConfigPath","targetPath","process","env","BABEL_SHOW_CONFIG_FOR","absolutePath","resolve","stats","fs","stat","isFile","Error"],"sources":["../../../src/config/files/configuration.ts"],"sourcesContent":["import buildDebug from \"debug\";\nimport nodeFs from \"fs\";\nimport path from \"path\";\nimport json5 from \"json5\";\nimport gensync from \"gensync\";\nimport type { Handler } from \"gensync\";\nimport { makeStrongCache, makeWeakCacheSync } from \"../caching\";\nimport type { CacheConfigurator } from \"../caching\";\nimport { makeConfigAPI } from \"../helpers/config-api\";\nimport type { ConfigAPI } from \"../helpers/config-api\";\nimport { makeStaticFileCache } from \"./utils\";\nimport loadCjsOrMjsDefault from \"./module-types\";\nimport pathPatternToRegex from \"../pattern-to-regex\";\nimport type { FilePackageData, RelativeConfig, ConfigFile } from \"./types\";\nimport type { CallerMetadata } from \"../validation/options\";\nimport ConfigError from \"../../errors/config-error\";\n\nimport * as fs from \"../../gensync-utils/fs\";\n\nimport { createRequire } from \"module\";\nimport { endHiddenCallStack } from \"../../errors/rewrite-stack-trace\";\nconst require = createRequire(import.meta.url);\n\nconst debug = buildDebug(\"babel:config:loading:files:configuration\");\n\nexport const ROOT_CONFIG_FILENAMES = [\n \"babel.config.js\",\n \"babel.config.cjs\",\n \"babel.config.mjs\",\n \"babel.config.json\",\n];\nconst RELATIVE_CONFIG_FILENAMES = [\n \".babelrc\",\n \".babelrc.js\",\n \".babelrc.cjs\",\n \".babelrc.mjs\",\n \".babelrc.json\",\n];\n\nconst BABELIGNORE_FILENAME = \".babelignore\";\n\nexport function findConfigUpwards(rootDir: string): string | null {\n let dirname = rootDir;\n for (;;) {\n for (const filename of ROOT_CONFIG_FILENAMES) {\n if (nodeFs.existsSync(path.join(dirname, filename))) {\n return dirname;\n }\n }\n\n const nextDir = path.dirname(dirname);\n if (dirname === nextDir) break;\n dirname = nextDir;\n }\n\n return null;\n}\n\nexport function* findRelativeConfig(\n packageData: FilePackageData,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler {\n let config = null;\n let ignore = null;\n\n const dirname = path.dirname(packageData.filepath);\n\n for (const loc of packageData.directories) {\n if (!config) {\n config = yield* loadOneConfig(\n RELATIVE_CONFIG_FILENAMES,\n loc,\n envName,\n caller,\n packageData.pkg?.dirname === loc\n ? packageToBabelConfig(packageData.pkg as ConfigFile)\n : null,\n );\n }\n\n if (!ignore) {\n const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);\n ignore = yield* readIgnoreConfig(ignoreLoc);\n\n if (ignore) {\n debug(\"Found ignore %o from %o.\", ignore.filepath, dirname);\n }\n }\n }\n\n return { config, ignore };\n}\n\nexport function findRootConfig(\n dirname: string,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler {\n return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller);\n}\n\nfunction* loadOneConfig(\n names: string[],\n dirname: string,\n envName: string,\n caller: CallerMetadata | undefined,\n previousConfig: ConfigFile | null = null,\n): Handler {\n const configs = yield* gensync.all(\n names.map(filename =>\n readConfig(path.join(dirname, filename), envName, caller),\n ),\n );\n const config = configs.reduce((previousConfig: ConfigFile | null, config) => {\n if (config && previousConfig) {\n throw new ConfigError(\n `Multiple configuration files found. Please remove one:\\n` +\n ` - ${path.basename(previousConfig.filepath)}\\n` +\n ` - ${config.filepath}\\n` +\n `from ${dirname}`,\n );\n }\n\n return config || previousConfig;\n }, previousConfig);\n\n if (config) {\n debug(\"Found configuration %o from %o.\", config.filepath, dirname);\n }\n return config;\n}\n\nexport function* loadConfig(\n name: string,\n dirname: string,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler {\n const filepath = require.resolve(name, { paths: [dirname] });\n\n const conf = yield* readConfig(filepath, envName, caller);\n if (!conf) {\n throw new ConfigError(\n `Config file contains no configuration data`,\n filepath,\n );\n }\n\n debug(\"Loaded config %o from %o.\", name, dirname);\n return conf;\n}\n\n/**\n * Read the given config file, returning the result. Returns null if no config was found, but will\n * throw if there are parsing errors while loading a config.\n */\nfunction readConfig(\n filepath: string,\n envName: string,\n caller: CallerMetadata | undefined,\n): Handler {\n const ext = path.extname(filepath);\n return ext === \".js\" || ext === \".cjs\" || ext === \".mjs\"\n ? readConfigJS(filepath, { envName, caller })\n : readConfigJSON5(filepath);\n}\n\nconst LOADING_CONFIGS = new Set();\n\nconst readConfigJS = makeStrongCache(function* readConfigJS(\n filepath: string,\n cache: CacheConfigurator<{\n envName: string;\n caller: CallerMetadata | undefined;\n }>,\n): Handler {\n if (!nodeFs.existsSync(filepath)) {\n cache.never();\n return null;\n }\n\n // The `require()` call below can make this code reentrant if a require hook like @babel/register has been\n // loaded into the system. That would cause Babel to attempt to compile the `.babelrc.js` file as it loads\n // below. To cover this case, we auto-ignore re-entrant config processing.\n if (LOADING_CONFIGS.has(filepath)) {\n cache.never();\n\n debug(\"Auto-ignoring usage of config %o.\", filepath);\n return {\n filepath,\n dirname: path.dirname(filepath),\n options: {},\n };\n }\n\n let options: unknown;\n try {\n LOADING_CONFIGS.add(filepath);\n options = yield* loadCjsOrMjsDefault(\n filepath,\n \"You appear to be using a native ECMAScript module configuration \" +\n \"file, which is only supported when running Babel asynchronously.\",\n );\n } finally {\n LOADING_CONFIGS.delete(filepath);\n }\n\n let assertCache = false;\n if (typeof options === \"function\") {\n // @ts-expect-error - if we want to make it possible to use async configs\n yield* [];\n\n options = endHiddenCallStack(options as any as (api: ConfigAPI) => {})(\n makeConfigAPI(cache),\n );\n\n assertCache = true;\n }\n\n if (!options || typeof options !== \"object\" || Array.isArray(options)) {\n throw new ConfigError(\n `Configuration should be an exported JavaScript object.`,\n filepath,\n );\n }\n\n // @ts-expect-error todo(flow->ts)\n if (typeof options.then === \"function\") {\n throw new ConfigError(\n `You appear to be using an async configuration, ` +\n `which your current version of Babel does not support. ` +\n `We may add support for this in the future, ` +\n `but if you're on the most recent version of @babel/core and still ` +\n `seeing this error, then you'll need to synchronously return your config.`,\n filepath,\n );\n }\n\n if (assertCache && !cache.configured()) throwConfigError(filepath);\n\n return {\n filepath,\n dirname: path.dirname(filepath),\n options,\n };\n});\n\nconst packageToBabelConfig = makeWeakCacheSync(\n (file: ConfigFile): ConfigFile | null => {\n const babel: unknown = file.options[\"babel\"];\n\n if (typeof babel === \"undefined\") return null;\n\n if (typeof babel !== \"object\" || Array.isArray(babel) || babel === null) {\n throw new ConfigError(`.babel property must be an object`, file.filepath);\n }\n\n return {\n filepath: file.filepath,\n dirname: file.dirname,\n options: babel,\n };\n },\n);\n\nconst readConfigJSON5 = makeStaticFileCache((filepath, content): ConfigFile => {\n let options;\n try {\n options = json5.parse(content);\n } catch (err) {\n throw new ConfigError(\n `Error while parsing config - ${err.message}`,\n filepath,\n );\n }\n\n if (!options) throw new ConfigError(`No config detected`, filepath);\n\n if (typeof options !== \"object\") {\n throw new ConfigError(`Config returned typeof ${typeof options}`, filepath);\n }\n if (Array.isArray(options)) {\n throw new ConfigError(`Expected config object but found array`, filepath);\n }\n\n delete options[\"$schema\"];\n\n return {\n filepath,\n dirname: path.dirname(filepath),\n options,\n };\n});\n\nconst readIgnoreConfig = makeStaticFileCache((filepath, content) => {\n const ignoreDir = path.dirname(filepath);\n const ignorePatterns = content\n .split(\"\\n\")\n .map(line => line.replace(/#(.*?)$/, \"\").trim())\n .filter(line => !!line);\n\n for (const pattern of ignorePatterns) {\n if (pattern[0] === \"!\") {\n throw new ConfigError(\n `Negation of file paths is not supported.`,\n filepath,\n );\n }\n }\n\n return {\n filepath,\n dirname: path.dirname(filepath),\n ignore: ignorePatterns.map(pattern =>\n pathPatternToRegex(pattern, ignoreDir),\n ),\n };\n});\n\nexport function* resolveShowConfigPath(\n dirname: string,\n): Handler {\n const targetPath = process.env.BABEL_SHOW_CONFIG_FOR;\n if (targetPath != null) {\n const absolutePath = path.resolve(dirname, targetPath);\n const stats = yield* fs.stat(absolutePath);\n if (!stats.isFile()) {\n throw new Error(\n `${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`,\n );\n }\n return absolutePath;\n }\n return null;\n}\n\nfunction throwConfigError(filepath: string): never {\n throw new ConfigError(\n `\\\nCaching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured\nfor various types of caching, using the first param of their handler functions:\n\nmodule.exports = function(api) {\n // The API exposes the following:\n\n // Cache the returned value forever and don't call this function again.\n api.cache(true);\n\n // Don't cache at all. Not recommended because it will be very slow.\n api.cache(false);\n\n // Cached based on the value of some function. If this function returns a value different from\n // a previously-encountered value, the plugins will re-evaluate.\n var env = api.cache(() => process.env.NODE_ENV);\n\n // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for\n // any possible NODE_ENV value that might come up during plugin execution.\n var isProd = api.cache(() => process.env.NODE_ENV === \"production\");\n\n // .cache(fn) will perform a linear search though instances to find the matching plugin based\n // based on previous instantiated plugins. If you want to recreate the plugin and discard the\n // previous instance whenever something changes, you may use:\n var isProd = api.cache.invalidate(() => process.env.NODE_ENV === \"production\");\n\n // Note, we also expose the following more-verbose versions of the above examples:\n api.cache.forever(); // api.cache(true)\n api.cache.never(); // api.cache(false)\n api.cache.using(fn); // api.cache(fn)\n\n // Return the value that will be cached.\n return { };\n};`,\n filepath,\n );\n}\n"],"mappings":";;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;;AAEA;;AAEA;;AACA;;AACA;;AAGA;;AAEA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;;AAGA,MAAMA,KAAK,GAAGC,QAAA,CAAW,0CAAX,CAAd;;AAEO,MAAMC,qBAAqB,GAAG,CACnC,iBADmC,EAEnC,kBAFmC,EAGnC,kBAHmC,EAInC,mBAJmC,CAA9B;;AAMP,MAAMC,yBAAyB,GAAG,CAChC,UADgC,EAEhC,aAFgC,EAGhC,cAHgC,EAIhC,cAJgC,EAKhC,eALgC,CAAlC;AAQA,MAAMC,oBAAoB,GAAG,cAA7B;;AAEO,SAASC,iBAAT,CAA2BC,OAA3B,EAA2D;EAChE,IAAIC,OAAO,G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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,GAlCQ,EAmCJjB,QAnCI,CAAN;AAqCD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/import-meta-resolve.js b/node_modules/@babel/core/lib/config/files/import-meta-resolve.js new file mode 100644 index 0000000..ea52f24 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/import-meta-resolve.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = resolve; + +function _module() { + const data = require("module"); + + _module = function () { + return data; + }; + + return data; +} + +var _importMetaResolve = require("../../vendor/import-meta-resolve"); + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +let import_; + +try { + import_ = require("./import.cjs"); +} catch (_unused) {} + +const importMetaResolveP = import_ && process.execArgv.includes("--experimental-import-meta-resolve") ? import_("data:text/javascript,export default import.meta.resolve").then(m => m.default || _importMetaResolve.resolve, () => _importMetaResolve.resolve) : Promise.resolve(_importMetaResolve.resolve); + +function resolve(_x, _x2) { + return _resolve.apply(this, arguments); +} + +function _resolve() { + _resolve = _asyncToGenerator(function* (specifier, parent) { + return (yield importMetaResolveP)(specifier, parent); + }); + return _resolve.apply(this, arguments); +} + +0 && 0; + +//# sourceMappingURL=import-meta-resolve.js.map diff --git a/node_modules/@babel/core/lib/config/files/import-meta-resolve.js.map b/node_modules/@babel/core/lib/config/files/import-meta-resolve.js.map new file mode 100644 index 0000000..0391dc0 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/import-meta-resolve.js.map @@ -0,0 +1 @@ +{"version":3,"names":["import_","require","importMetaResolveP","process","execArgv","includes","then","m","default","polyfill","Promise","resolve","specifier","parent"],"sources":["../../../src/config/files/import-meta-resolve.ts"],"sourcesContent":["import { createRequire } from \"module\";\nimport { resolve as polyfill } from \"../../vendor/import-meta-resolve\";\n\nconst require = createRequire(import.meta.url);\n\nlet import_;\ntry {\n // Node < 13.3 doesn't support import() syntax.\n import_ = require(\"./import.cjs\");\n} catch {}\n\n// import.meta.resolve is only available in ESM, but this file is compiled to CJS.\n// We can extract it using dynamic import.\nconst importMetaResolveP: Promise =\n import_ &&\n // Due to a Node.js/V8 bug (https://github.com/nodejs/node/issues/35889), we cannot\n // use always dynamic import because it segfaults when running in a Node.js `vm` context,\n // which is used by the default Jest environment and by webpack-cli.\n //\n // However, import.meta.resolve is experimental and only enabled when Node.js is run\n // with the `--experimental-import-meta-resolve` flag: we can avoid calling import()\n // when that flag is not enabled, so that the default behavior never segfaults.\n //\n // Hopefully, before Node.js unflags import.meta.resolve, either:\n // - we will move to ESM, so that we have direct access to import.meta.resolve, or\n // - the V8 bug will be fixed so that we can safely use dynamic import by default.\n //\n // I (@nicolo-ribaudo) am really anoyed by this bug, because there is no known\n // work-around other than \"don't use dynamic import if you are running in a `vm` context\",\n // but there is no reliable way to detect it (you cannot try/catch segfaults).\n //\n // This is the only place where we *need* to use dynamic import because we need to access\n // an ES module. All the other places will first try using require() and *then*, if\n // it throws because it's a module, will fallback to import().\n process.execArgv.includes(\"--experimental-import-meta-resolve\")\n ? import_(\"data:text/javascript,export default import.meta.resolve\").then(\n (m: { default: ImportMeta[\"resolve\"] | undefined }) =>\n m.default || polyfill,\n () => polyfill,\n )\n : Promise.resolve(polyfill);\n\nexport default async function resolve(\n specifier: Parameters[0],\n parent?: Parameters[1],\n): ReturnType {\n return (await importMetaResolveP)(specifier, parent);\n}\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;;;;;;AAIA,IAAIA,OAAJ;;AACA,IAAI;EAEFA,OAAO,GAAGC,OAAO,CAAC,cAAD,CAAjB;AACD,CAHD,CAGE,gBAAM,CAAE;;AAIV,MAAMC,kBAAkD,GACtDF,OAAO,IAoBPG,OAAO,CAACC,QAAR,CAAiBC,QAAjB,CAA0B,oCAA1B,CApBA,GAqBIL,OAAO,CAAC,yDAAD,CAAP,CAAmEM,IAAnE,CACGC,CAAD,IACEA,CAAC,CAACC,OAAF,IAAaC,0BAFjB,EAGE,MAAMA,0BAHR,CArBJ,GA0BIC,OAAO,CAACC,OAAR,CAAgBF,0BAAhB,CA3BN;;SA6B8BE,O;;;;;+BAAf,WACbC,SADa,EAEbC,MAFa,EAGsB;IACnC,OAAO,OAAOX,kBAAP,EAA2BU,SAA3B,EAAsCC,MAAtC,CAAP;EACD,C"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/import.cjs b/node_modules/@babel/core/lib/config/files/import.cjs new file mode 100644 index 0000000..c66e76c --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/import.cjs @@ -0,0 +1,7 @@ +module.exports = function import_(filepath) { + return import(filepath); +}; + +0 && 0; + +//# sourceMappingURL=import.cjs.map diff --git a/node_modules/@babel/core/lib/config/files/import.cjs.map b/node_modules/@babel/core/lib/config/files/import.cjs.map new file mode 100644 index 0000000..a872a81 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/import.cjs.map @@ -0,0 +1 @@ +{"version":3,"names":["module","exports","import_","filepath"],"sources":["../../../src/config/files/import.cjs"],"sourcesContent":["// We keep this in a separate file so that in older node versions, where\n// import() isn't supported, we can try/catch around the require() call\n// when loading this file.\n\nmodule.exports = function import_(filepath) {\n return import(filepath);\n};\n"],"mappings":"AAIAA,MAAM,CAACC,OAAP,GAAiB,SAASC,OAAT,CAAiBC,QAAjB,EAA2B;EAC1C,OAAO,OAAOA,QAAP,CAAP;AACD,CAFD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/index-browser.js b/node_modules/@babel/core/lib/config/files/index-browser.js new file mode 100644 index 0000000..c8d1cf9 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/index-browser.js @@ -0,0 +1,71 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ROOT_CONFIG_FILENAMES = void 0; +exports.findConfigUpwards = findConfigUpwards; +exports.findPackageData = findPackageData; +exports.findRelativeConfig = findRelativeConfig; +exports.findRootConfig = findRootConfig; +exports.loadConfig = loadConfig; +exports.loadPlugin = loadPlugin; +exports.loadPreset = loadPreset; +exports.resolvePlugin = resolvePlugin; +exports.resolvePreset = resolvePreset; +exports.resolveShowConfigPath = resolveShowConfigPath; + +function findConfigUpwards(rootDir) { + return null; +} + +function* findPackageData(filepath) { + return { + filepath, + directories: [], + pkg: null, + isPackage: false + }; +} + +function* findRelativeConfig(pkgData, envName, caller) { + return { + config: null, + ignore: null + }; +} + +function* findRootConfig(dirname, envName, caller) { + return null; +} + +function* loadConfig(name, dirname, envName, caller) { + throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`); +} + +function* resolveShowConfigPath(dirname) { + return null; +} + +const ROOT_CONFIG_FILENAMES = []; +exports.ROOT_CONFIG_FILENAMES = ROOT_CONFIG_FILENAMES; + +function resolvePlugin(name, dirname) { + return null; +} + +function resolvePreset(name, dirname) { + return null; +} + +function loadPlugin(name, dirname) { + throw new Error(`Cannot load plugin ${name} relative to ${dirname} in a browser`); +} + +function loadPreset(name, dirname) { + throw new Error(`Cannot load preset ${name} relative to ${dirname} in a browser`); +} + +0 && 0; + +//# sourceMappingURL=index-browser.js.map diff --git a/node_modules/@babel/core/lib/config/files/index-browser.js.map b/node_modules/@babel/core/lib/config/files/index-browser.js.map new file mode 100644 index 0000000..2ed5e1d --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/index-browser.js.map @@ -0,0 +1 @@ +{"version":3,"names":["findConfigUpwards","rootDir","findPackageData","filepath","directories","pkg","isPackage","findRelativeConfig","pkgData","envName","caller","config","ignore","findRootConfig","dirname","loadConfig","name","Error","resolveShowConfigPath","ROOT_CONFIG_FILENAMES","resolvePlugin","resolvePreset","loadPlugin","loadPreset"],"sources":["../../../src/config/files/index-browser.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport type {\n ConfigFile,\n IgnoreFile,\n RelativeConfig,\n FilePackageData,\n} from \"./types\";\n\nimport type { CallerMetadata } from \"../validation/options\";\n\nexport type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData };\n\nexport function findConfigUpwards(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rootDir: string,\n): string | null {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* findPackageData(filepath: string): Handler {\n return {\n filepath,\n directories: [],\n pkg: null,\n isPackage: false,\n };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRelativeConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n pkgData: FilePackageData,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler {\n return { config: null, ignore: null };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRootConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* loadConfig(\n name: string,\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler {\n throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);\n}\n\n// eslint-disable-next-line require-yield\nexport function* resolveShowConfigPath(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n): Handler {\n return null;\n}\n\nexport const ROOT_CONFIG_FILENAMES: string[] = [];\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePlugin(name: string, dirname: string): string | null {\n return null;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePreset(name: string, dirname: string): string | null {\n return null;\n}\n\nexport function loadPlugin(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load plugin ${name} relative to ${dirname} in a browser`,\n );\n}\n\nexport function loadPreset(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load preset ${name} relative to ${dirname} in a browser`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAaO,SAASA,iBAAT,CAELC,OAFK,EAGU;EACf,OAAO,IAAP;AACD;;AAGM,UAAUC,eAAV,CAA0BC,QAA1B,EAAsE;EAC3E,OAAO;IACLA,QADK;IAELC,WAAW,EAAE,EAFR;IAGLC,GAAG,EAAE,IAHA;IAILC,SAAS,EAAE;EAJN,CAAP;AAMD;;AAGM,UAAUC,kBAAV,CAELC,OAFK,EAILC,OAJK,EAMLC,MANK,EAOoB;EACzB,OAAO;IAAEC,MAAM,EAAE,IAAV;IAAgBC,MAAM,EAAE;EAAxB,CAAP;AACD;;AAGM,UAAUC,cAAV,CAELC,OAFK,EAILL,OAJK,EAMLC,MANK,EAOuB;EAC5B,OAAO,IAAP;AACD;;AAGM,UAAUK,UAAV,CACLC,IADK,EAELF,OAFK,EAILL,OAJK,EAMLC,MANK,EAOgB;EACrB,MAAM,IAAIO,KAAJ,CAAW,eAAcD,IAAK,gBAAeF,OAAQ,eAArD,CAAN;AACD;;AAGM,UAAUI,qBAAV,CAELJ,OAFK,EAGmB;EACxB,OAAO,IAAP;AACD;;AAEM,MAAMK,qBAA+B,GAAG,EAAxC;;;AAGA,SAASC,aAAT,CAAuBJ,IAAvB,EAAqCF,OAArC,EAAqE;EAC1E,OAAO,IAAP;AACD;;AAGM,SAASO,aAAT,CAAuBL,IAAvB,EAAqCF,OAArC,EAAqE;EAC1E,OAAO,IAAP;AACD;;AAEM,SAASQ,UAAT,CACLN,IADK,EAELF,OAFK,EAMJ;EACD,MAAM,IAAIG,KAAJ,CACH,sBAAqBD,IAAK,gBAAeF,OAAQ,eAD9C,CAAN;AAGD;;AAEM,SAASS,UAAT,CACLP,IADK,EAELF,OAFK,EAMJ;EACD,MAAM,IAAIG,KAAJ,CACH,sBAAqBD,IAAK,gBAAeF,OAAQ,eAD9C,CAAN;AAGD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/index.js b/node_modules/@babel/core/lib/config/files/index.js new file mode 100644 index 0000000..c6acd93 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/index.js @@ -0,0 +1,89 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "ROOT_CONFIG_FILENAMES", { + enumerable: true, + get: function () { + return _configuration.ROOT_CONFIG_FILENAMES; + } +}); +Object.defineProperty(exports, "findConfigUpwards", { + enumerable: true, + get: function () { + return _configuration.findConfigUpwards; + } +}); +Object.defineProperty(exports, "findPackageData", { + enumerable: true, + get: function () { + return _package.findPackageData; + } +}); +Object.defineProperty(exports, "findRelativeConfig", { + enumerable: true, + get: function () { + return _configuration.findRelativeConfig; + } +}); +Object.defineProperty(exports, "findRootConfig", { + enumerable: true, + get: function () { + return _configuration.findRootConfig; + } +}); +Object.defineProperty(exports, "loadConfig", { + enumerable: true, + get: function () { + return _configuration.loadConfig; + } +}); +Object.defineProperty(exports, "loadPlugin", { + enumerable: true, + get: function () { + return plugins.loadPlugin; + } +}); +Object.defineProperty(exports, "loadPreset", { + enumerable: true, + get: function () { + return plugins.loadPreset; + } +}); +exports.resolvePreset = exports.resolvePlugin = void 0; +Object.defineProperty(exports, "resolveShowConfigPath", { + enumerable: true, + get: function () { + return _configuration.resolveShowConfigPath; + } +}); + +var _package = require("./package"); + +var _configuration = require("./configuration"); + +var plugins = require("./plugins"); + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +({}); + +const resolvePlugin = _gensync()(plugins.resolvePlugin).sync; + +exports.resolvePlugin = resolvePlugin; + +const resolvePreset = _gensync()(plugins.resolvePreset).sync; + +exports.resolvePreset = resolvePreset; +0 && 0; + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/core/lib/config/files/index.js.map b/node_modules/@babel/core/lib/config/files/index.js.map new file mode 100644 index 0000000..2fba62f --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["resolvePlugin","gensync","plugins","sync","resolvePreset"],"sources":["../../../src/config/files/index.ts"],"sourcesContent":["type indexBrowserType = typeof import(\"./index-browser\");\ntype indexType = typeof import(\"./index\");\n\n// Kind of gross, but essentially asserting that the exports of this module are the same as the\n// exports of index-browser, since this file may be replaced at bundle time with index-browser.\n({} as any as indexBrowserType as indexType);\n\nexport { findPackageData } from \"./package\";\n\nexport {\n findConfigUpwards,\n findRelativeConfig,\n findRootConfig,\n loadConfig,\n resolveShowConfigPath,\n ROOT_CONFIG_FILENAMES,\n} from \"./configuration\";\nexport type {\n ConfigFile,\n IgnoreFile,\n RelativeConfig,\n FilePackageData,\n} from \"./types\";\nexport { loadPlugin, loadPreset } from \"./plugins\";\n\nimport gensync from \"gensync\";\nimport * as plugins from \"./plugins\";\n\nexport const resolvePlugin = gensync(plugins.resolvePlugin).sync;\nexport const resolvePreset = gensync(plugins.resolvePreset).sync;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA;;AAEA;;AAcA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AApBA,CAAC,EAAD;;AAuBO,MAAMA,aAAa,GAAGC,UAAA,CAAQC,OAAO,CAACF,aAAhB,EAA+BG,IAArD;;;;AACA,MAAMC,aAAa,GAAGH,UAAA,CAAQC,OAAO,CAACE,aAAhB,EAA+BD,IAArD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/module-types.js b/node_modules/@babel/core/lib/config/files/module-types.js new file mode 100644 index 0000000..e443507 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/module-types.js @@ -0,0 +1,126 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadCjsOrMjsDefault; +exports.supportsESM = void 0; + +var _async = require("../../gensync-utils/async"); + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _url() { + const data = require("url"); + + _url = function () { + return data; + }; + + return data; +} + +function _module() { + const data = require("module"); + + _module = function () { + return data; + }; + + return data; +} + +function _semver() { + const data = require("semver"); + + _semver = function () { + return data; + }; + + return data; +} + +var _rewriteStackTrace = require("../../errors/rewrite-stack-trace"); + +var _configError = require("../../errors/config-error"); + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +let import_; + +try { + import_ = require("./import.cjs"); +} catch (_unused) {} + +const supportsESM = _semver().satisfies(process.versions.node, "^12.17 || >=13.2"); + +exports.supportsESM = supportsESM; + +function* loadCjsOrMjsDefault(filepath, asyncError, fallbackToTranspiledModule = false) { + switch (guessJSModuleType(filepath)) { + case "cjs": + return loadCjsDefault(filepath, fallbackToTranspiledModule); + + case "unknown": + try { + return loadCjsDefault(filepath, fallbackToTranspiledModule); + } catch (e) { + if (e.code !== "ERR_REQUIRE_ESM") throw e; + } + + case "mjs": + if (yield* (0, _async.isAsync)()) { + return yield* (0, _async.waitFor)(loadMjsDefault(filepath)); + } + + throw new _configError.default(asyncError, filepath); + } +} + +function guessJSModuleType(filename) { + switch (_path().extname(filename)) { + case ".cjs": + return "cjs"; + + case ".mjs": + return "mjs"; + + default: + return "unknown"; + } +} + +function loadCjsDefault(filepath, fallbackToTranspiledModule) { + const module = (0, _rewriteStackTrace.endHiddenCallStack)(require)(filepath); + return module != null && module.__esModule ? module.default || (fallbackToTranspiledModule ? module : undefined) : module; +} + +function loadMjsDefault(_x) { + return _loadMjsDefault.apply(this, arguments); +} + +function _loadMjsDefault() { + _loadMjsDefault = _asyncToGenerator(function* (filepath) { + if (!import_) { + throw new _configError.default("Internal error: Native ECMAScript modules aren't supported" + " by this platform.\n", filepath); + } + + const module = yield (0, _rewriteStackTrace.endHiddenCallStack)(import_)((0, _url().pathToFileURL)(filepath)); + return module.default; + }); + return _loadMjsDefault.apply(this, arguments); +} + +0 && 0; + +//# sourceMappingURL=module-types.js.map diff --git a/node_modules/@babel/core/lib/config/files/module-types.js.map b/node_modules/@babel/core/lib/config/files/module-types.js.map new file mode 100644 index 0000000..012928d --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/module-types.js.map @@ -0,0 +1 @@ +{"version":3,"names":["import_","require","supportsESM","semver","satisfies","process","versions","node","loadCjsOrMjsDefault","filepath","asyncError","fallbackToTranspiledModule","guessJSModuleType","loadCjsDefault","e","code","isAsync","waitFor","loadMjsDefault","ConfigError","filename","path","extname","module","endHiddenCallStack","__esModule","default","undefined","pathToFileURL"],"sources":["../../../src/config/files/module-types.ts"],"sourcesContent":["import { isAsync, waitFor } from \"../../gensync-utils/async\";\nimport type { Handler } from \"gensync\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { createRequire } from \"module\";\nimport semver from \"semver\";\n\nimport { endHiddenCallStack } from \"../../errors/rewrite-stack-trace\";\nimport ConfigError from \"../../errors/config-error\";\n\nconst require = createRequire(import.meta.url);\n\nlet import_: ((specifier: string | URL) => any) | undefined;\ntry {\n // Old Node.js versions don't support import() syntax.\n import_ = require(\"./import.cjs\");\n} catch {}\n\nexport const supportsESM = semver.satisfies(\n process.versions.node,\n // older versions, starting from 10, support the dynamic\n // import syntax but always return a rejected promise.\n \"^12.17 || >=13.2\",\n);\n\nexport default function* loadCjsOrMjsDefault(\n filepath: string,\n asyncError: string,\n // TODO(Babel 8): Remove this\n fallbackToTranspiledModule: boolean = false,\n): Handler {\n switch (guessJSModuleType(filepath)) {\n case \"cjs\":\n return loadCjsDefault(filepath, fallbackToTranspiledModule);\n case \"unknown\":\n try {\n return loadCjsDefault(filepath, fallbackToTranspiledModule);\n } catch (e) {\n if (e.code !== \"ERR_REQUIRE_ESM\") throw e;\n }\n // fall through\n case \"mjs\":\n if (yield* isAsync()) {\n return yield* waitFor(loadMjsDefault(filepath));\n }\n throw new ConfigError(asyncError, filepath);\n }\n}\n\nfunction guessJSModuleType(filename: string): \"cjs\" | \"mjs\" | \"unknown\" {\n switch (path.extname(filename)) {\n case \".cjs\":\n return \"cjs\";\n case \".mjs\":\n return \"mjs\";\n default:\n return \"unknown\";\n }\n}\n\nfunction loadCjsDefault(filepath: string, fallbackToTranspiledModule: boolean) {\n const module = endHiddenCallStack(require)(filepath) as any;\n return module?.__esModule\n ? // TODO (Babel 8): Remove \"module\" and \"undefined\" fallback\n module.default || (fallbackToTranspiledModule ? module : undefined)\n : module;\n}\n\nasync function loadMjsDefault(filepath: string) {\n if (!import_) {\n throw new ConfigError(\n \"Internal error: Native ECMAScript modules aren't supported\" +\n \" by this platform.\\n\",\n filepath,\n );\n }\n\n // import() expects URLs, not file paths.\n // https://github.com/nodejs/node/issues/31710\n const module = await endHiddenCallStack(import_)(pathToFileURL(filepath));\n return module.default;\n}\n"],"mappings":";;;;;;;;AAAA;;AAEA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EA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AM,GAAG,IAAAC,qCAAA,EAAmBvB,OAAnB,EAA4BQ,QAA5B,CAAf;EACA,OAAOc,MAAM,QAAN,IAAAA,MAAM,CAAEE,UAAR,GAEHF,MAAM,CAACG,OAAP,KAAmBf,0BAA0B,GAAGY,MAAH,GAAYI,SAAzD,CAFG,GAGHJ,MAHJ;AAID;;SAEcL,c;;;;;sCAAf,WAA8BT,QAA9B,EAAgD;IAC9C,IAAI,CAACT,OAAL,EAAc;MACZ,MAAM,IAAImB,oBAAJ,CACJ,+DACE,sBAFE,EAGJV,QAHI,CAAN;IAKD;;IAID,MAAMc,MAAM,SAAS,IAAAC,qCAAA,EAAmBxB,OAAnB,EAA4B,IAAA4B,oBAAA,EAAcnB,QAAd,CAA5B,CAArB;IACA,OAAOc,MAAM,CAACG,OAAd;EACD,C"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/package.js b/node_modules/@babel/core/lib/config/files/package.js new file mode 100644 index 0000000..c5108b8 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/package.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findPackageData = findPackageData; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +var _utils = require("./utils"); + +var _configError = require("../../errors/config-error"); + +const PACKAGE_FILENAME = "package.json"; + +function* findPackageData(filepath) { + let pkg = null; + const directories = []; + let isPackage = true; + + let dirname = _path().dirname(filepath); + + while (!pkg && _path().basename(dirname) !== "node_modules") { + directories.push(dirname); + pkg = yield* readConfigPackage(_path().join(dirname, PACKAGE_FILENAME)); + + const nextLoc = _path().dirname(dirname); + + if (dirname === nextLoc) { + isPackage = false; + break; + } + + dirname = nextLoc; + } + + return { + filepath, + directories, + pkg, + isPackage + }; +} + +const readConfigPackage = (0, _utils.makeStaticFileCache)((filepath, content) => { + let options; + + try { + options = JSON.parse(content); + } catch (err) { + throw new _configError.default(`Error while parsing JSON - ${err.message}`, filepath); + } + + if (!options) throw new Error(`${filepath}: No config detected`); + + if (typeof options !== "object") { + throw new _configError.default(`Config returned typeof ${typeof options}`, filepath); + } + + if (Array.isArray(options)) { + throw new _configError.default(`Expected config object but found array`, filepath); + } + + return { + filepath, + dirname: _path().dirname(filepath), + options + }; +}); +0 && 0; + +//# sourceMappingURL=package.js.map diff --git a/node_modules/@babel/core/lib/config/files/package.js.map b/node_modules/@babel/core/lib/config/files/package.js.map new file mode 100644 index 0000000..05fe1fb --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/package.js.map @@ -0,0 +1 @@ +{"version":3,"names":["PACKAGE_FILENAME","findPackageData","filepath","pkg","directories","isPackage","dirname","path","basename","push","readConfigPackage","join","nextLoc","makeStaticFileCache","content","options","JSON","parse","err","ConfigError","message","Error","Array","isArray"],"sources":["../../../src/config/files/package.ts"],"sourcesContent":["import path from \"path\";\nimport type { Handler } from \"gensync\";\nimport { makeStaticFileCache } from \"./utils\";\n\nimport type { ConfigFile, FilePackageData } from \"./types\";\n\nimport ConfigError from \"../../errors/config-error\";\n\nconst PACKAGE_FILENAME = \"package.json\";\n\n/**\n * Find metadata about the package that this file is inside of. Resolution\n * of Babel's config requires general package information to decide when to\n * search for .babelrc files\n */\nexport function* findPackageData(filepath: string): Handler {\n let pkg = null;\n const directories = [];\n let isPackage = true;\n\n let dirname = path.dirname(filepath);\n while (!pkg && path.basename(dirname) !== \"node_modules\") {\n directories.push(dirname);\n\n pkg = yield* readConfigPackage(path.join(dirname, PACKAGE_FILENAME));\n\n const nextLoc = path.dirname(dirname);\n if (dirname === nextLoc) {\n isPackage = false;\n break;\n }\n dirname = nextLoc;\n }\n\n return { filepath, directories, pkg, isPackage };\n}\n\nconst readConfigPackage = makeStaticFileCache(\n (filepath, content): ConfigFile => {\n let options;\n try {\n options = JSON.parse(content) as unknown;\n } catch (err) {\n throw new ConfigError(\n `Error while parsing JSON - ${err.message}`,\n filepath,\n );\n }\n\n if (!options) throw new Error(`${filepath}: No config detected`);\n\n if (typeof options !== \"object\") {\n throw new ConfigError(\n `Config returned typeof ${typeof options}`,\n filepath,\n );\n }\n if (Array.isArray(options)) {\n throw new ConfigError(`Expected config object but found array`, filepath);\n }\n\n return {\n filepath,\n dirname: path.dirname(filepath),\n options,\n };\n },\n);\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;;AAIA;;AAEA,MAAMA,gBAAgB,GAAG,cAAzB;;AAOO,UAAUC,eAAV,CAA0BC,QAA1B,EAAsE;EAC3E,IAAIC,GAAG,GAAG,IAAV;EACA,MAAMC,WAAW,GAAG,EAApB;EACA,IAAIC,SAAS,GAAG,IAAhB;;EAEA,IAAIC,OAAO,GAAGC,OAAA,CAAKD,OAAL,CAAaJ,QAAb,CAAd;;EACA,OAAO,CAACC,GAAD,IAAQI,OAAA,CAAKC,QAAL,CAAcF,OAAd,MAA2B,cAA1C,EAA0D;IACxDF,WAAW,CAACK,IAAZ,CAAiBH,OAAjB;IAEAH,GAAG,GAAG,OAAOO,iBAAiB,CAACH,OAAA,CAAKI,IAAL,CAAUL,OAAV,EAAmBN,gBAAnB,CAAD,CAA9B;;IAEA,MAAMY,OAAO,GAAGL,OAAA,CAAKD,OAAL,CAAaA,OAAb,CAAhB;;IACA,IAAIA,OAAO,KAAKM,OAAhB,EAAyB;MACvBP,SAAS,GAAG,KAAZ;MACA;IACD;;IACDC,OAAO,GAAGM,OAAV;EACD;;EAED,OAAO;IAAEV,QAAF;IAAYE,WAAZ;IAAyBD,GAAzB;IAA8BE;EAA9B,CAAP;AACD;;AAED,MAAMK,iBAAiB,GAAG,IAAAG,0BAAA,EACxB,CAACX,QAAD,EAAWY,OAAX,KAAmC;EACjC,IAAIC,OAAJ;;EACA,IAAI;IACFA,OAAO,GAAGC,IAAI,CAACC,KAAL,CAAWH,OAAX,CAAV;EACD,CAFD,CAEE,OAAOI,GAAP,EAAY;IACZ,MAAM,IAAIC,oBAAJ,CACH,8BAA6BD,GAAG,CAACE,OAAQ,EADtC,EAEJlB,QAFI,CAAN;EAID;;EAED,IAAI,CAACa,OAAL,EAAc,MAAM,IAAIM,KAAJ,CAAW,GAAEnB,QAAS,sBAAtB,CAAN;;EAEd,IAAI,OAAOa,OAAP,KAAmB,QAAvB,EAAiC;IAC/B,MAAM,IAAII,oBAAJ,CACH,0BAAyB,OAAOJ,OAAQ,EADrC,EAEJb,QAFI,CAAN;EAID;;EACD,IAAIoB,KAAK,CAACC,OAAN,CAAcR,OAAd,CAAJ,EAA4B;IAC1B,MAAM,IAAII,oBAAJ,CAAiB,wCAAjB,EAA0DjB,QAA1D,CAAN;EACD;;EAED,OAAO;IACLA,QADK;IAELI,OAAO,EAAEC,OAAA,CAAKD,OAAL,CAAaJ,QAAb,CAFJ;IAGLa;EAHK,CAAP;AAKD,CA7BuB,CAA1B"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/plugins.js b/node_modules/@babel/core/lib/config/files/plugins.js new file mode 100644 index 0000000..327eb7d --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/plugins.js @@ -0,0 +1,277 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.loadPlugin = loadPlugin; +exports.loadPreset = loadPreset; +exports.resolvePlugin = resolvePlugin; +exports.resolvePreset = resolvePreset; + +function _debug() { + const data = require("debug"); + + _debug = function () { + return data; + }; + + return data; +} + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _async = require("../../gensync-utils/async"); + +var _moduleTypes = require("./module-types"); + +function _url() { + const data = require("url"); + + _url = function () { + return data; + }; + + return data; +} + +var _importMetaResolve = require("./import-meta-resolve"); + +function _module() { + const data = require("module"); + + _module = function () { + return data; + }; + + return data; +} + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +const debug = _debug()("babel:config:loading:files:plugins"); + +const EXACT_RE = /^module:/; +const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/; +const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/; +const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/; +const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/; +const OTHER_PLUGIN_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/; +const OTHER_PRESET_ORG_RE = /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/; +const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/; + +function* resolvePlugin(name, dirname) { + return yield* resolveStandardizedName("plugin", name, dirname); +} + +function* resolvePreset(name, dirname) { + return yield* resolveStandardizedName("preset", name, dirname); +} + +function* loadPlugin(name, dirname) { + const filepath = yield* resolvePlugin(name, dirname); + const value = yield* requireModule("plugin", filepath); + debug("Loaded plugin %o from %o.", name, dirname); + return { + filepath, + value + }; +} + +function* loadPreset(name, dirname) { + const filepath = yield* resolvePreset(name, dirname); + const value = yield* requireModule("preset", filepath); + debug("Loaded preset %o from %o.", name, dirname); + return { + filepath, + value + }; +} + +function standardizeName(type, name) { + if (_path().isAbsolute(name)) return name; + const isPreset = type === "preset"; + return name.replace(isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE, `babel-${type}-`).replace(isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE, `$1${type}-`).replace(isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE, `$1babel-${type}-`).replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`).replace(EXACT_RE, ""); +} + +function* resolveAlternativesHelper(type, name) { + const standardizedName = standardizeName(type, name); + const { + error, + value + } = yield standardizedName; + if (!error) return value; + if (error.code !== "MODULE_NOT_FOUND") throw error; + + if (standardizedName !== name && !(yield name).error) { + error.message += `\n- If you want to resolve "${name}", use "module:${name}"`; + } + + if (!(yield standardizeName(type, "@babel/" + name)).error) { + error.message += `\n- Did you mean "@babel/${name}"?`; + } + + const oppositeType = type === "preset" ? "plugin" : "preset"; + + if (!(yield standardizeName(oppositeType, name)).error) { + error.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`; + } + + throw error; +} + +function tryRequireResolve(id, { + paths: [dirname] +}) { + try { + return { + error: null, + value: (((v, w) => (v = v.split("."), w = w.split("."), +v[0] > +w[0] || v[0] == w[0] && +v[1] >= +w[1]))(process.versions.node, "8.9") ? require.resolve : (r, { + paths: [b] + }, M = require("module")) => { + let f = M._findPath(r, M._nodeModulePaths(b).concat(b)); + + if (f) return f; + f = new Error(`Cannot resolve module '${r}'`); + f.code = "MODULE_NOT_FOUND"; + throw f; + })(id, { + paths: [dirname] + }) + }; + } catch (error) { + return { + error, + value: null + }; + } +} + +function tryImportMetaResolve(_x, _x2) { + return _tryImportMetaResolve.apply(this, arguments); +} + +function _tryImportMetaResolve() { + _tryImportMetaResolve = _asyncToGenerator(function* (id, options) { + try { + return { + error: null, + value: yield (0, _importMetaResolve.default)(id, options) + }; + } catch (error) { + return { + error, + value: null + }; + } + }); + return _tryImportMetaResolve.apply(this, arguments); +} + +function resolveStandardizedNameForRequire(type, name, dirname) { + const it = resolveAlternativesHelper(type, name); + let res = it.next(); + + while (!res.done) { + res = it.next(tryRequireResolve(res.value, { + paths: [dirname] + })); + } + + return res.value; +} + +function resolveStandardizedNameForImport(_x3, _x4, _x5) { + return _resolveStandardizedNameForImport.apply(this, arguments); +} + +function _resolveStandardizedNameForImport() { + _resolveStandardizedNameForImport = _asyncToGenerator(function* (type, name, dirname) { + const parentUrl = (0, _url().pathToFileURL)(_path().join(dirname, "./babel-virtual-resolve-base.js")).href; + const it = resolveAlternativesHelper(type, name); + let res = it.next(); + + while (!res.done) { + res = it.next(yield tryImportMetaResolve(res.value, parentUrl)); + } + + return (0, _url().fileURLToPath)(res.value); + }); + return _resolveStandardizedNameForImport.apply(this, arguments); +} + +const resolveStandardizedName = _gensync()({ + sync(type, name, dirname = process.cwd()) { + return resolveStandardizedNameForRequire(type, name, dirname); + }, + + async(type, name, dirname = process.cwd()) { + return _asyncToGenerator(function* () { + if (!_moduleTypes.supportsESM) { + return resolveStandardizedNameForRequire(type, name, dirname); + } + + try { + return yield resolveStandardizedNameForImport(type, name, dirname); + } catch (e) { + try { + return resolveStandardizedNameForRequire(type, name, dirname); + } catch (e2) { + if (e.type === "MODULE_NOT_FOUND") throw e; + if (e2.type === "MODULE_NOT_FOUND") throw e2; + throw e; + } + } + })(); + } + +}); + +{ + var LOADING_MODULES = new Set(); +} + +function* requireModule(type, name) { + { + if (!(yield* (0, _async.isAsync)()) && LOADING_MODULES.has(name)) { + throw new Error(`Reentrant ${type} detected trying to load "${name}". This module is not ignored ` + "and is trying to load itself while compiling itself, leading to a dependency cycle. " + 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.'); + } + } + + try { + { + LOADING_MODULES.add(name); + } + return yield* (0, _moduleTypes.default)(name, `You appear to be using a native ECMAScript module ${type}, ` + "which is only supported when running Babel asynchronously.", true); + } catch (err) { + err.message = `[BABEL]: ${err.message} (While processing: ${name})`; + throw err; + } finally { + { + LOADING_MODULES.delete(name); + } + } +} + +0 && 0; + +//# sourceMappingURL=plugins.js.map diff --git a/node_modules/@babel/core/lib/config/files/plugins.js.map b/node_modules/@babel/core/lib/config/files/plugins.js.map new file mode 100644 index 0000000..2ef528e --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/plugins.js.map @@ -0,0 +1 @@ +{"version":3,"names":["debug","buildDebug","EXACT_RE","BABEL_PLUGIN_PREFIX_RE","BABEL_PRESET_PREFIX_RE","BABEL_PLUGIN_ORG_RE","BABEL_PRESET_ORG_RE","OTHER_PLUGIN_ORG_RE","OTHER_PRESET_ORG_RE","OTHER_ORG_DEFAULT_RE","resolvePlugin","name","dirname","resolveStandardizedName","resolvePreset","loadPlugin","filepath","value","requireModule","loadPreset","standardizeName","type","path","isAbsolute","isPreset","replace","resolveAlternativesHelper","standardizedName","error","code","message","oppositeType","tryRequireResolve","id","paths","tryImportMetaResolve","options","importMetaResolve","resolveStandardizedNameForRequire","it","res","next","done","resolveStandardizedNameForImport","parentUrl","pathToFileURL","join","href","fileURLToPath","gensync","sync","process","cwd","async","supportsESM","e","e2","LOADING_MODULES","Set","isAsync","has","Error","add","loadCjsOrMjsDefault","err","delete"],"sources":["../../../src/config/files/plugins.ts"],"sourcesContent":["/**\n * This file handles all logic for converting string-based configuration references into loaded objects.\n */\n\nimport buildDebug from \"debug\";\nimport path from \"path\";\nimport gensync, { type Handler } from \"gensync\";\nimport { isAsync } from \"../../gensync-utils/async\";\nimport loadCjsOrMjsDefault, { supportsESM } from \"./module-types\";\nimport { fileURLToPath, pathToFileURL } from \"url\";\n\nimport importMetaResolve from \"./import-meta-resolve\";\n\nimport { createRequire } from \"module\";\nconst require = createRequire(import.meta.url);\n\nconst debug = buildDebug(\"babel:config:loading:files:plugins\");\n\nconst EXACT_RE = /^module:/;\nconst BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\\/|babel-plugin-)/;\nconst BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\\/|babel-preset-)/;\nconst BABEL_PLUGIN_ORG_RE = /^(@babel\\/)(?!plugin-|[^/]+\\/)/;\nconst BABEL_PRESET_ORG_RE = /^(@babel\\/)(?!preset-|[^/]+\\/)/;\nconst OTHER_PLUGIN_ORG_RE =\n /^(@(?!babel\\/)[^/]+\\/)(?![^/]*babel-plugin(?:-|\\/|$)|[^/]+\\/)/;\nconst OTHER_PRESET_ORG_RE =\n /^(@(?!babel\\/)[^/]+\\/)(?![^/]*babel-preset(?:-|\\/|$)|[^/]+\\/)/;\nconst OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;\n\nexport function* resolvePlugin(name: string, dirname: string): Handler {\n return yield* resolveStandardizedName(\"plugin\", name, dirname);\n}\n\nexport function* resolvePreset(name: string, dirname: string): Handler {\n return yield* resolveStandardizedName(\"preset\", name, dirname);\n}\n\nexport function* loadPlugin(\n name: string,\n dirname: string,\n): Handler<{ filepath: string; value: unknown }> {\n const filepath = yield* resolvePlugin(name, dirname);\n\n const value = yield* requireModule(\"plugin\", filepath);\n debug(\"Loaded plugin %o from %o.\", name, dirname);\n\n return { filepath, value };\n}\n\nexport function* loadPreset(\n name: string,\n dirname: string,\n): Handler<{ filepath: string; value: unknown }> {\n const filepath = yield* resolvePreset(name, dirname);\n\n const value = yield* requireModule(\"preset\", filepath);\n\n debug(\"Loaded preset %o from %o.\", name, dirname);\n\n return { filepath, value };\n}\n\nfunction standardizeName(type: \"plugin\" | \"preset\", name: string) {\n // Let absolute and relative paths through.\n if (path.isAbsolute(name)) return name;\n\n const isPreset = type === \"preset\";\n\n return (\n name\n // foo -> babel-preset-foo\n .replace(\n isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE,\n `babel-${type}-`,\n )\n // @babel/es2015 -> @babel/preset-es2015\n .replace(\n isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE,\n `$1${type}-`,\n )\n // @foo/mypreset -> @foo/babel-preset-mypreset\n .replace(\n isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE,\n `$1babel-${type}-`,\n )\n // @foo -> @foo/babel-preset\n .replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`)\n // module:mypreset -> mypreset\n .replace(EXACT_RE, \"\")\n );\n}\n\ntype Result = { error: Error; value: null } | { error: null; value: T };\n\nfunction* resolveAlternativesHelper(\n type: \"plugin\" | \"preset\",\n name: string,\n): Iterator> {\n const standardizedName = standardizeName(type, name);\n const { error, value } = yield standardizedName;\n if (!error) return value;\n\n // @ts-expect-error code may not index error\n if (error.code !== \"MODULE_NOT_FOUND\") throw error;\n\n if (standardizedName !== name && !(yield name).error) {\n error.message += `\\n- If you want to resolve \"${name}\", use \"module:${name}\"`;\n }\n\n if (!(yield standardizeName(type, \"@babel/\" + name)).error) {\n error.message += `\\n- Did you mean \"@babel/${name}\"?`;\n }\n\n const oppositeType = type === \"preset\" ? \"plugin\" : \"preset\";\n if (!(yield standardizeName(oppositeType, name)).error) {\n error.message += `\\n- Did you accidentally pass a ${oppositeType} as a ${type}?`;\n }\n\n throw error;\n}\n\nfunction tryRequireResolve(\n id: Parameters[0],\n { paths: [dirname] }: Parameters[1],\n): Result {\n try {\n return { error: null, value: require.resolve(id, { paths: [dirname] }) };\n } catch (error) {\n return { error, value: null };\n }\n}\n\nasync function tryImportMetaResolve(\n id: Parameters[0],\n options: Parameters[1],\n): Promise> {\n try {\n return { error: null, value: await importMetaResolve(id, options) };\n } catch (error) {\n return { error, value: null };\n }\n}\n\nfunction resolveStandardizedNameForRequire(\n type: \"plugin\" | \"preset\",\n name: string,\n dirname: string,\n) {\n const it = resolveAlternativesHelper(type, name);\n let res = it.next();\n while (!res.done) {\n res = it.next(tryRequireResolve(res.value, { paths: [dirname] }));\n }\n return res.value;\n}\nasync function resolveStandardizedNameForImport(\n type: \"plugin\" | \"preset\",\n name: string,\n dirname: string,\n) {\n const parentUrl = pathToFileURL(\n path.join(dirname, \"./babel-virtual-resolve-base.js\"),\n ).href;\n\n const it = resolveAlternativesHelper(type, name);\n let res = it.next();\n while (!res.done) {\n res = it.next(await tryImportMetaResolve(res.value, parentUrl));\n }\n return fileURLToPath(res.value);\n}\n\nconst resolveStandardizedName = gensync<\n [type: \"plugin\" | \"preset\", name: string, dirname?: string],\n string\n>({\n sync(type, name, dirname = process.cwd()) {\n return resolveStandardizedNameForRequire(type, name, dirname);\n },\n async async(type, name, dirname = process.cwd()) {\n if (!supportsESM) {\n return resolveStandardizedNameForRequire(type, name, dirname);\n }\n\n try {\n return await resolveStandardizedNameForImport(type, name, dirname);\n } catch (e) {\n try {\n return resolveStandardizedNameForRequire(type, name, dirname);\n } catch (e2) {\n if (e.type === \"MODULE_NOT_FOUND\") throw e;\n if (e2.type === \"MODULE_NOT_FOUND\") throw e2;\n throw e;\n }\n }\n },\n});\n\nif (!process.env.BABEL_8_BREAKING) {\n // eslint-disable-next-line no-var\n var LOADING_MODULES = new Set();\n}\nfunction* requireModule(type: string, name: string): Handler {\n if (!process.env.BABEL_8_BREAKING) {\n if (!(yield* isAsync()) && LOADING_MODULES.has(name)) {\n throw new Error(\n `Reentrant ${type} detected trying to load \"${name}\". This module is not ignored ` +\n \"and is trying to load itself while compiling itself, leading to a dependency cycle. \" +\n 'We recommend adding it to your \"ignore\" list in your babelrc, or to a .babelignore.',\n );\n }\n }\n\n try {\n if (!process.env.BABEL_8_BREAKING) {\n LOADING_MODULES.add(name);\n }\n return yield* loadCjsOrMjsDefault(\n name,\n `You appear to be using a native ECMAScript module ${type}, ` +\n \"which is only supported when running Babel asynchronously.\",\n // For backward compatibility, we need to support malformed presets\n // defined as separate named exports rather than a single default\n // export.\n // See packages/babel-core/test/fixtures/option-manager/presets/es2015_named.js\n true,\n );\n } catch (err) {\n err.message = `[BABEL]: ${err.message} (While processing: ${name})`;\n throw err;\n } finally {\n if (!process.env.BABEL_8_BREAKING) {\n LOADING_MODULES.delete(name);\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAIA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;;AACA;;AACA;EAAA;;EA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FD,CAEE,OAAO2C,CAAP,EAAU;QACV,IAAI;UACF,OAAOjB,iCAAiC,CAACjB,IAAD,EAAOV,IAAP,EAAaC,OAAb,CAAxC;QACD,CAFD,CAEE,OAAO4C,EAAP,EAAW;UACX,IAAID,CAAC,CAAClC,IAAF,KAAW,kBAAf,EAAmC,MAAMkC,CAAN;UACnC,IAAIC,EAAE,CAACnC,IAAH,KAAY,kBAAhB,EAAoC,MAAMmC,EAAN;UACpC,MAAMD,CAAN;QACD;MACF;IAf8C;EAgBhD;;AApBD,CAH8B,CAAhC;;AA0BmC;EAEjC,IAAIE,eAAe,GAAG,IAAIC,GAAJ,EAAtB;AACD;;AACD,UAAUxC,aAAV,CAAwBG,IAAxB,EAAsCV,IAAtC,EAAsE;EACjC;IACjC,IAAI,EAAE,OAAO,IAAAgD,cAAA,GAAT,KAAuBF,eAAe,CAACG,GAAhB,CAAoBjD,IAApB,CAA3B,EAAsD;MACpD,MAAM,IAAIkD,KAAJ,CACH,aAAYxC,IAAK,6BAA4BV,IAAK,gCAAnD,GACE,sFADF,GAEE,qFAHE,CAAN;IAKD;EACF;;EAED,IAAI;IACiC;MACjC8C,eAAe,CAACK,GAAhB,CAAoBnD,IAApB;IACD;IACD,OAAO,OAAO,IAAAoD,oBAAA,EACZpD,IADY,EAEX,qDAAoDU,IAAK,IAA1D,GACE,4DAHU,EAQZ,IARY,CAAd;EAUD,CAdD,CAcE,OAAO2C,GAAP,EAAY;IACZA,GAAG,CAAClC,OAAJ,GAAe,YAAWkC,GAAG,CAAClC,OAAQ,uBAAsBnB,IAAK,GAAjE;IACA,MAAMqD,GAAN;EACD,CAjBD,SAiBU;IAC2B;MACjCP,eAAe,CAACQ,MAAhB,CAAuBtD,IAAvB;IACD;EACF;AACF"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/types.js b/node_modules/@babel/core/lib/config/files/types.js new file mode 100644 index 0000000..c03b5a6 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/types.js @@ -0,0 +1,3 @@ +0 && 0; + +//# sourceMappingURL=types.js.map diff --git a/node_modules/@babel/core/lib/config/files/types.js.map b/node_modules/@babel/core/lib/config/files/types.js.map new file mode 100644 index 0000000..107e58c --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/types.js.map @@ -0,0 +1 @@ +{"version":3,"names":[],"sources":["../../../src/config/files/types.ts"],"sourcesContent":["import type { InputOptions } from \"..\";\n\nexport type ConfigFile = {\n filepath: string;\n dirname: string;\n options: InputOptions & { babel?: unknown };\n};\n\nexport type IgnoreFile = {\n filepath: string;\n dirname: string;\n ignore: Array;\n};\n\nexport type RelativeConfig = {\n // The actual config, either from package.json#babel, .babelrc, or\n // .babelrc.js, if there was one.\n config: ConfigFile | null;\n // The .babelignore, if there was one.\n ignore: IgnoreFile | null;\n};\n\nexport type FilePackageData = {\n // The file in the package.\n filepath: string;\n // Any ancestor directories of the file that are within the package.\n directories: Array;\n // The contents of the package.json. May not be found if the package just\n // terminated at a node_modules folder without finding one.\n pkg: ConfigFile | null;\n // True if a package.json or node_modules folder was found while traversing\n // the directory structure.\n isPackage: boolean;\n};\n"],"mappings":""} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/files/utils.js b/node_modules/@babel/core/lib/config/files/utils.js new file mode 100644 index 0000000..e60f0be --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/utils.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.makeStaticFileCache = makeStaticFileCache; + +var _caching = require("../caching"); + +var fs = require("../../gensync-utils/fs"); + +function _fs2() { + const data = require("fs"); + + _fs2 = function () { + return data; + }; + + return data; +} + +function makeStaticFileCache(fn) { + return (0, _caching.makeStrongCache)(function* (filepath, cache) { + const cached = cache.invalidate(() => fileMtime(filepath)); + + if (cached === null) { + return null; + } + + return fn(filepath, yield* fs.readFile(filepath, "utf8")); + }); +} + +function fileMtime(filepath) { + if (!_fs2().existsSync(filepath)) return null; + + try { + return +_fs2().statSync(filepath).mtime; + } catch (e) { + if (e.code !== "ENOENT" && e.code !== "ENOTDIR") throw e; + } + + return null; +} + +0 && 0; + +//# sourceMappingURL=utils.js.map diff --git a/node_modules/@babel/core/lib/config/files/utils.js.map b/node_modules/@babel/core/lib/config/files/utils.js.map new file mode 100644 index 0000000..36a6a37 --- /dev/null +++ b/node_modules/@babel/core/lib/config/files/utils.js.map @@ -0,0 +1 @@ +{"version":3,"names":["makeStaticFileCache","fn","makeStrongCache","filepath","cache","cached","invalidate","fileMtime","fs","readFile","nodeFs","existsSync","statSync","mtime","e","code"],"sources":["../../../src/config/files/utils.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport { makeStrongCache } from \"../caching\";\nimport type { CacheConfigurator } from \"../caching\";\nimport * as fs from \"../../gensync-utils/fs\";\nimport nodeFs from \"fs\";\n\nexport function makeStaticFileCache(\n fn: (filepath: string, contents: string) => T,\n) {\n return makeStrongCache(function* (\n filepath: string,\n cache: CacheConfigurator,\n ): Handler {\n const cached = cache.invalidate(() => fileMtime(filepath));\n\n if (cached === null) {\n return null;\n }\n\n return fn(filepath, yield* fs.readFile(filepath, \"utf8\"));\n });\n}\n\nfunction fileMtime(filepath: string): number | null {\n if (!nodeFs.existsSync(filepath)) return null;\n\n try {\n return +nodeFs.statSync(filepath).mtime;\n } catch (e) {\n if (e.code !== \"ENOENT\" && e.code !== \"ENOTDIR\") throw e;\n }\n\n return null;\n}\n"],"mappings":";;;;;;;AAEA;;AAEA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEO,SAASA,mBAAT,CACLC,EADK,EAEL;EACA,OAAO,IAAAC,wBAAA,EAAgB,WACrBC,QADqB,EAErBC,KAFqB,EAGF;IACnB,MAAMC,MAAM,GAAGD,KAAK,CAACE,UAAN,CAAiB,MAAMC,SAAS,CAACJ,QAAD,CAAhC,CAAf;;IAEA,IAAIE,MAAM,KAAK,IAAf,EAAqB;MACnB,OAAO,IAAP;IACD;;IAED,OAAOJ,EAAE,CAACE,QAAD,EAAW,OAAOK,EAAE,CAACC,QAAH,CAAYN,QAAZ,EAAsB,MAAtB,CAAlB,CAAT;EACD,CAXM,CAAP;AAYD;;AAED,SAASI,SAAT,CAAmBJ,QAAnB,EAAoD;EAClD,IAAI,CAACO,MAAA,CAAOC,UAAP,CAAkBR,QAAlB,CAAL,EAAkC,OAAO,IAAP;;EAElC,IAAI;IACF,OAAO,CAACO,MAAA,CAAOE,QAAP,CAAgBT,QAAhB,EAA0BU,KAAlC;EACD,CAFD,CAEE,OAAOC,CAAP,EAAU;IACV,IAAIA,CAAC,CAACC,IAAF,KAAW,QAAX,IAAuBD,CAAC,CAACC,IAAF,KAAW,SAAtC,EAAiD,MAAMD,CAAN;EAClD;;EAED,OAAO,IAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/full.js b/node_modules/@babel/core/lib/config/full.js new file mode 100644 index 0000000..9beecff --- /dev/null +++ b/node_modules/@babel/core/lib/config/full.js @@ -0,0 +1,386 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _async = require("../gensync-utils/async"); + +var _util = require("./util"); + +var context = require("../index"); + +var _plugin = require("./plugin"); + +var _item = require("./item"); + +var _configChain = require("./config-chain"); + +var _deepArray = require("./helpers/deep-array"); + +function _traverse() { + const data = require("@babel/traverse"); + + _traverse = function () { + return data; + }; + + return data; +} + +var _caching = require("./caching"); + +var _options = require("./validation/options"); + +var _plugins = require("./validation/plugins"); + +var _configApi = require("./helpers/config-api"); + +var _partial = require("./partial"); + +var _configError = require("../errors/config-error"); + +var _default = _gensync()(function* loadFullConfig(inputOpts) { + var _opts$assumptions; + + const result = yield* (0, _partial.default)(inputOpts); + + if (!result) { + return null; + } + + const { + options, + context, + fileHandling + } = result; + + if (fileHandling === "ignored") { + return null; + } + + const optionDefaults = {}; + const { + plugins, + presets + } = options; + + if (!plugins || !presets) { + throw new Error("Assertion failure - plugins and presets exist"); + } + + const presetContext = Object.assign({}, context, { + targets: options.targets + }); + + const toDescriptor = item => { + const desc = (0, _item.getItemDescriptor)(item); + + if (!desc) { + throw new Error("Assertion failure - must be config item"); + } + + return desc; + }; + + const presetsDescriptors = presets.map(toDescriptor); + const initialPluginsDescriptors = plugins.map(toDescriptor); + const pluginDescriptorsByPass = [[]]; + const passes = []; + const externalDependencies = []; + const ignored = yield* enhanceError(context, function* recursePresetDescriptors(rawPresets, pluginDescriptorsPass) { + const presets = []; + + for (let i = 0; i < rawPresets.length; i++) { + const descriptor = rawPresets[i]; + + if (descriptor.options !== false) { + try { + var preset = yield* loadPresetDescriptor(descriptor, presetContext); + } catch (e) { + if (e.code === "BABEL_UNKNOWN_OPTION") { + (0, _options.checkNoUnwrappedItemOptionPairs)(rawPresets, i, "preset", e); + } + + throw e; + } + + externalDependencies.push(preset.externalDependencies); + + if (descriptor.ownPass) { + presets.push({ + preset: preset.chain, + pass: [] + }); + } else { + presets.unshift({ + preset: preset.chain, + pass: pluginDescriptorsPass + }); + } + } + } + + if (presets.length > 0) { + pluginDescriptorsByPass.splice(1, 0, ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass)); + + for (const { + preset, + pass + } of presets) { + if (!preset) return true; + pass.push(...preset.plugins); + const ignored = yield* recursePresetDescriptors(preset.presets, pass); + if (ignored) return true; + preset.options.forEach(opts => { + (0, _util.mergeOptions)(optionDefaults, opts); + }); + } + } + })(presetsDescriptors, pluginDescriptorsByPass[0]); + if (ignored) return null; + const opts = optionDefaults; + (0, _util.mergeOptions)(opts, options); + const pluginContext = Object.assign({}, presetContext, { + assumptions: (_opts$assumptions = opts.assumptions) != null ? _opts$assumptions : {} + }); + yield* enhanceError(context, function* loadPluginDescriptors() { + pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors); + + for (const descs of pluginDescriptorsByPass) { + const pass = []; + passes.push(pass); + + for (let i = 0; i < descs.length; i++) { + const descriptor = descs[i]; + + if (descriptor.options !== false) { + try { + var plugin = yield* loadPluginDescriptor(descriptor, pluginContext); + } catch (e) { + if (e.code === "BABEL_UNKNOWN_PLUGIN_PROPERTY") { + (0, _options.checkNoUnwrappedItemOptionPairs)(descs, i, "plugin", e); + } + + throw e; + } + + pass.push(plugin); + externalDependencies.push(plugin.externalDependencies); + } + } + } + })(); + opts.plugins = passes[0]; + opts.presets = passes.slice(1).filter(plugins => plugins.length > 0).map(plugins => ({ + plugins + })); + opts.passPerPreset = opts.presets.length > 0; + return { + options: opts, + passes: passes, + externalDependencies: (0, _deepArray.finalize)(externalDependencies) + }; +}); + +exports.default = _default; + +function enhanceError(context, fn) { + return function* (arg1, arg2) { + try { + return yield* fn(arg1, arg2); + } catch (e) { + if (!/^\[BABEL\]/.test(e.message)) { + var _context$filename; + + e.message = `[BABEL] ${(_context$filename = context.filename) != null ? _context$filename : "unknown file"}: ${e.message}`; + } + + throw e; + } + }; +} + +const makeDescriptorLoader = apiFactory => (0, _caching.makeWeakCache)(function* ({ + value, + options, + dirname, + alias +}, cache) { + if (options === false) throw new Error("Assertion failure"); + options = options || {}; + const externalDependencies = []; + let item = value; + + if (typeof value === "function") { + const factory = (0, _async.maybeAsync)(value, `You appear to be using an async plugin/preset, but Babel has been called synchronously`); + const api = Object.assign({}, context, apiFactory(cache, externalDependencies)); + + try { + item = yield* factory(api, options, dirname); + } catch (e) { + if (alias) { + e.message += ` (While processing: ${JSON.stringify(alias)})`; + } + + throw e; + } + } + + if (!item || typeof item !== "object") { + throw new Error("Plugin/Preset did not return an object."); + } + + if ((0, _async.isThenable)(item)) { + yield* []; + throw new Error(`You appear to be using a promise as a plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version. ` + `As an alternative, you can prefix the promise with "await". ` + `(While processing: ${JSON.stringify(alias)})`); + } + + if (externalDependencies.length > 0 && (!cache.configured() || cache.mode() === "forever")) { + let error = `A plugin/preset has external untracked dependencies ` + `(${externalDependencies[0]}), but the cache `; + + if (!cache.configured()) { + error += `has not been configured to be invalidated when the external dependencies change. `; + } else { + error += ` has been configured to never be invalidated. `; + } + + error += `Plugins/presets should configure their cache to be invalidated when the external ` + `dependencies change, for example using \`api.cache.invalidate(() => ` + `statSync(filepath).mtimeMs)\` or \`api.cache.never()\`\n` + `(While processing: ${JSON.stringify(alias)})`; + throw new Error(error); + } + + return { + value: item, + options, + dirname, + alias, + externalDependencies: (0, _deepArray.finalize)(externalDependencies) + }; +}); + +const pluginDescriptorLoader = makeDescriptorLoader(_configApi.makePluginAPI); +const presetDescriptorLoader = makeDescriptorLoader(_configApi.makePresetAPI); + +function* loadPluginDescriptor(descriptor, context) { + if (descriptor.value instanceof _plugin.default) { + if (descriptor.options) { + throw new Error("Passed options to an existing Plugin instance will not work."); + } + + return descriptor.value; + } + + return yield* instantiatePlugin(yield* pluginDescriptorLoader(descriptor, context), context); +} + +const instantiatePlugin = (0, _caching.makeWeakCache)(function* ({ + value, + options, + dirname, + alias, + externalDependencies +}, cache) { + const pluginObj = (0, _plugins.validatePluginObject)(value); + const plugin = Object.assign({}, pluginObj); + + if (plugin.visitor) { + plugin.visitor = _traverse().default.explode(Object.assign({}, plugin.visitor)); + } + + if (plugin.inherits) { + const inheritsDescriptor = { + name: undefined, + alias: `${alias}$inherits`, + value: plugin.inherits, + options, + dirname + }; + const inherits = yield* (0, _async.forwardAsync)(loadPluginDescriptor, run => { + return cache.invalidate(data => run(inheritsDescriptor, data)); + }); + plugin.pre = chain(inherits.pre, plugin.pre); + plugin.post = chain(inherits.post, plugin.post); + plugin.manipulateOptions = chain(inherits.manipulateOptions, plugin.manipulateOptions); + plugin.visitor = _traverse().default.visitors.merge([inherits.visitor || {}, plugin.visitor || {}]); + + if (inherits.externalDependencies.length > 0) { + if (externalDependencies.length === 0) { + externalDependencies = inherits.externalDependencies; + } else { + externalDependencies = (0, _deepArray.finalize)([externalDependencies, inherits.externalDependencies]); + } + } + } + + return new _plugin.default(plugin, options, alias, externalDependencies); +}); + +const needsFilename = val => val && typeof val !== "function"; + +const validateIfOptionNeedsFilename = (options, descriptor) => { + if (needsFilename(options.test) || needsFilename(options.include) || needsFilename(options.exclude)) { + const formattedPresetName = descriptor.name ? `"${descriptor.name}"` : "/* your preset */"; + throw new _configError.default([`Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`, `\`\`\``, `babel.transformSync(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`, `\`\`\``, `See https://babeljs.io/docs/en/options#filename for more information.`].join("\n")); + } +}; + +const validatePreset = (preset, context, descriptor) => { + if (!context.filename) { + const { + options + } = preset; + validateIfOptionNeedsFilename(options, descriptor); + + if (options.overrides) { + options.overrides.forEach(overrideOptions => validateIfOptionNeedsFilename(overrideOptions, descriptor)); + } + } +}; + +function* loadPresetDescriptor(descriptor, context) { + const preset = instantiatePreset(yield* presetDescriptorLoader(descriptor, context)); + validatePreset(preset, context, descriptor); + return { + chain: yield* (0, _configChain.buildPresetChain)(preset, context), + externalDependencies: preset.externalDependencies + }; +} + +const instantiatePreset = (0, _caching.makeWeakCacheSync)(({ + value, + dirname, + alias, + externalDependencies +}) => { + return { + options: (0, _options.validate)("preset", value), + alias, + dirname, + externalDependencies + }; +}); + +function chain(a, b) { + const fns = [a, b].filter(Boolean); + if (fns.length <= 1) return fns[0]; + return function (...args) { + for (const fn of fns) { + fn.apply(this, args); + } + }; +} + +0 && 0; + +//# sourceMappingURL=full.js.map diff --git a/node_modules/@babel/core/lib/config/full.js.map b/node_modules/@babel/core/lib/config/full.js.map new file mode 100644 index 0000000..9bacc40 --- /dev/null +++ b/node_modules/@babel/core/lib/config/full.js.map @@ -0,0 +1 @@ +{"version":3,"names":["gensync","loadFullConfig","inputOpts","result","loadPrivatePartialConfig","options","context","fileHandling","optionDefaults","plugins","presets","Error","presetContext","targets","toDescriptor","item","desc","getItemDescriptor","presetsDescriptors","map","initialPluginsDescriptors","pluginDescriptorsByPass","passes","externalDependencies","ignored","enhanceError","recursePresetDescriptors","rawPresets","pluginDescriptorsPass","i","length","descriptor","preset","loadPresetDescriptor","e","code","checkNoUnwrappedItemOptionPairs","push","ownPass","chain","pass","unshift","splice","o","filter","p","forEach","opts","mergeOptions","pluginContext","assumptions","loadPluginDescriptors","descs","plugin","loadPluginDescriptor","slice","passPerPreset","freezeDeepArray","fn","arg1","arg2","test","message","filename","makeDescriptorLoader","apiFactory","makeWeakCache","value","dirname","alias","cache","factory","maybeAsync","api","JSON","stringify","isThenable","configured","mode","error","pluginDescriptorLoader","makePluginAPI","presetDescriptorLoader","makePresetAPI","Plugin","instantiatePlugin","pluginObj","validatePluginObject","visitor","traverse","explode","inherits","inheritsDescriptor","name","undefined","forwardAsync","run","invalidate","data","pre","post","manipulateOptions","visitors","merge","needsFilename","val","validateIfOptionNeedsFilename","include","exclude","formattedPresetName","ConfigError","join","validatePreset","overrides","overrideOptions","instantiatePreset","buildPresetChain","makeWeakCacheSync","validate","a","b","fns","Boolean","args","apply"],"sources":["../../src/config/full.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\nimport { forwardAsync, maybeAsync, isThenable } from \"../gensync-utils/async\";\n\nimport { mergeOptions } from \"./util\";\nimport * as context from \"../index\";\nimport Plugin from \"./plugin\";\nimport { getItemDescriptor } from \"./item\";\nimport { buildPresetChain } from \"./config-chain\";\nimport { finalize as freezeDeepArray } from \"./helpers/deep-array\";\nimport type { DeepArray, ReadonlyDeepArray } from \"./helpers/deep-array\";\nimport type {\n ConfigContext,\n ConfigChain,\n PresetInstance,\n} from \"./config-chain\";\nimport type { UnloadedDescriptor } from \"./config-descriptors\";\nimport traverse from \"@babel/traverse\";\nimport { makeWeakCache, makeWeakCacheSync } from \"./caching\";\nimport type { CacheConfigurator } from \"./caching\";\nimport {\n validate,\n checkNoUnwrappedItemOptionPairs,\n} from \"./validation/options\";\nimport type { PluginItem } from \"./validation/options\";\nimport { validatePluginObject } from \"./validation/plugins\";\nimport { makePluginAPI, makePresetAPI } from \"./helpers/config-api\";\nimport type { PluginAPI, PresetAPI } from \"./helpers/config-api\";\n\nimport loadPrivatePartialConfig from \"./partial\";\nimport type { ValidatedOptions } from \"./validation/options\";\n\nimport type * as Context from \"./cache-contexts\";\nimport ConfigError from \"../errors/config-error\";\n\ntype LoadedDescriptor = {\n value: {};\n options: {};\n dirname: string;\n alias: string;\n externalDependencies: ReadonlyDeepArray;\n};\n\nexport type { InputOptions } from \"./validation/options\";\n\nexport type ResolvedConfig = {\n options: any;\n passes: PluginPasses;\n externalDependencies: ReadonlyDeepArray;\n};\n\nexport type { Plugin };\nexport type PluginPassList = Array;\nexport type PluginPasses = Array;\n\nexport default gensync(function* loadFullConfig(\n inputOpts: unknown,\n): Handler {\n const result = yield* loadPrivatePartialConfig(inputOpts);\n if (!result) {\n return null;\n }\n const { options, context, fileHandling } = result;\n\n if (fileHandling === \"ignored\") {\n return null;\n }\n\n const optionDefaults = {};\n\n const { plugins, presets } = options;\n\n if (!plugins || !presets) {\n throw new Error(\"Assertion failure - plugins and presets exist\");\n }\n\n const presetContext: Context.FullPreset = {\n ...context,\n targets: options.targets,\n };\n\n const toDescriptor = (item: PluginItem) => {\n const desc = getItemDescriptor(item);\n if (!desc) {\n throw new Error(\"Assertion failure - must be config item\");\n }\n\n return desc;\n };\n\n const presetsDescriptors = presets.map(toDescriptor);\n const initialPluginsDescriptors = plugins.map(toDescriptor);\n const pluginDescriptorsByPass: Array> = [[]];\n const passes: Array> = [];\n\n const externalDependencies: DeepArray = [];\n\n const ignored = yield* enhanceError(\n context,\n function* recursePresetDescriptors(\n rawPresets: Array,\n pluginDescriptorsPass: Array,\n ): Handler {\n const presets: Array<{\n preset: ConfigChain | null;\n pass: Array;\n }> = [];\n\n for (let i = 0; i < rawPresets.length; i++) {\n const descriptor = rawPresets[i];\n if (descriptor.options !== false) {\n try {\n // eslint-disable-next-line no-var\n var preset = yield* loadPresetDescriptor(descriptor, presetContext);\n } catch (e) {\n if (e.code === \"BABEL_UNKNOWN_OPTION\") {\n checkNoUnwrappedItemOptionPairs(rawPresets, i, \"preset\", e);\n }\n throw e;\n }\n\n externalDependencies.push(preset.externalDependencies);\n\n // Presets normally run in reverse order, but if they\n // have their own pass they run after the presets\n // in the previous pass.\n if (descriptor.ownPass) {\n presets.push({ preset: preset.chain, pass: [] });\n } else {\n presets.unshift({\n preset: preset.chain,\n pass: pluginDescriptorsPass,\n });\n }\n }\n }\n\n // resolve presets\n if (presets.length > 0) {\n // The passes are created in the same order as the preset list, but are inserted before any\n // existing additional passes.\n pluginDescriptorsByPass.splice(\n 1,\n 0,\n ...presets.map(o => o.pass).filter(p => p !== pluginDescriptorsPass),\n );\n\n for (const { preset, pass } of presets) {\n if (!preset) return true;\n\n pass.push(...preset.plugins);\n\n const ignored = yield* recursePresetDescriptors(preset.presets, pass);\n if (ignored) return true;\n\n preset.options.forEach(opts => {\n mergeOptions(optionDefaults, opts);\n });\n }\n }\n },\n )(presetsDescriptors, pluginDescriptorsByPass[0]);\n\n if (ignored) return null;\n\n const opts: any = optionDefaults;\n mergeOptions(opts, options);\n\n const pluginContext: Context.FullPlugin = {\n ...presetContext,\n assumptions: opts.assumptions ?? {},\n };\n\n yield* enhanceError(context, function* loadPluginDescriptors() {\n pluginDescriptorsByPass[0].unshift(...initialPluginsDescriptors);\n\n for (const descs of pluginDescriptorsByPass) {\n const pass: Plugin[] = [];\n passes.push(pass);\n\n for (let i = 0; i < descs.length; i++) {\n const descriptor: UnloadedDescriptor = descs[i];\n if (descriptor.options !== false) {\n try {\n // eslint-disable-next-line no-var\n var plugin = yield* loadPluginDescriptor(descriptor, pluginContext);\n } catch (e) {\n if (e.code === \"BABEL_UNKNOWN_PLUGIN_PROPERTY\") {\n // print special message for `plugins: [\"@babel/foo\", { foo: \"option\" }]`\n checkNoUnwrappedItemOptionPairs(descs, i, \"plugin\", e);\n }\n throw e;\n }\n pass.push(plugin);\n\n externalDependencies.push(plugin.externalDependencies);\n }\n }\n }\n })();\n\n opts.plugins = passes[0];\n opts.presets = passes\n .slice(1)\n .filter(plugins => plugins.length > 0)\n .map(plugins => ({ plugins }));\n opts.passPerPreset = opts.presets.length > 0;\n\n return {\n options: opts,\n passes: passes,\n externalDependencies: freezeDeepArray(externalDependencies),\n };\n});\n\nfunction enhanceError(context: ConfigContext, fn: T): T {\n return function* (arg1: unknown, arg2: unknown) {\n try {\n return yield* fn(arg1, arg2);\n } catch (e) {\n // There are a few case where thrown errors will try to annotate themselves multiple times, so\n // to keep things simple we just bail out if re-wrapping the message.\n if (!/^\\[BABEL\\]/.test(e.message)) {\n e.message = `[BABEL] ${context.filename ?? \"unknown file\"}: ${\n e.message\n }`;\n }\n\n throw e;\n }\n } as any;\n}\n\n/**\n * Load a generic plugin/preset from the given descriptor loaded from the config object.\n */\nconst makeDescriptorLoader = (\n apiFactory: (\n cache: CacheConfigurator,\n externalDependencies: Array,\n ) => API,\n) =>\n makeWeakCache(function* (\n { value, options, dirname, alias }: UnloadedDescriptor,\n cache: CacheConfigurator,\n ): Handler {\n // Disabled presets should already have been filtered out\n if (options === false) throw new Error(\"Assertion failure\");\n\n options = options || {};\n\n const externalDependencies: Array = [];\n\n let item = value;\n if (typeof value === \"function\") {\n const factory = maybeAsync(\n value,\n `You appear to be using an async plugin/preset, but Babel has been called synchronously`,\n );\n\n const api = {\n ...context,\n ...apiFactory(cache, externalDependencies),\n };\n try {\n item = yield* factory(api, options, dirname);\n } catch (e) {\n if (alias) {\n e.message += ` (While processing: ${JSON.stringify(alias)})`;\n }\n throw e;\n }\n }\n\n if (!item || typeof item !== \"object\") {\n throw new Error(\"Plugin/Preset did not return an object.\");\n }\n\n if (isThenable(item)) {\n // @ts-expect-error - if we want to support async plugins\n yield* [];\n\n throw new Error(\n `You appear to be using a promise as a plugin, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, ` +\n `you may need to upgrade your @babel/core version. ` +\n `As an alternative, you can prefix the promise with \"await\". ` +\n `(While processing: ${JSON.stringify(alias)})`,\n );\n }\n\n if (\n externalDependencies.length > 0 &&\n (!cache.configured() || cache.mode() === \"forever\")\n ) {\n let error =\n `A plugin/preset has external untracked dependencies ` +\n `(${externalDependencies[0]}), but the cache `;\n if (!cache.configured()) {\n error += `has not been configured to be invalidated when the external dependencies change. `;\n } else {\n error += ` has been configured to never be invalidated. `;\n }\n error +=\n `Plugins/presets should configure their cache to be invalidated when the external ` +\n `dependencies change, for example using \\`api.cache.invalidate(() => ` +\n `statSync(filepath).mtimeMs)\\` or \\`api.cache.never()\\`\\n` +\n `(While processing: ${JSON.stringify(alias)})`;\n\n throw new Error(error);\n }\n\n return {\n value: item,\n options,\n dirname,\n alias,\n externalDependencies: freezeDeepArray(externalDependencies),\n };\n });\n\nconst pluginDescriptorLoader = makeDescriptorLoader<\n Context.SimplePlugin,\n PluginAPI\n>(makePluginAPI);\nconst presetDescriptorLoader = makeDescriptorLoader<\n Context.SimplePreset,\n PresetAPI\n>(makePresetAPI);\n\n/**\n * Instantiate a plugin for the given descriptor, returning the plugin/options pair.\n */\nfunction* loadPluginDescriptor(\n descriptor: UnloadedDescriptor,\n context: Context.SimplePlugin,\n): Handler {\n if (descriptor.value instanceof Plugin) {\n if (descriptor.options) {\n throw new Error(\n \"Passed options to an existing Plugin instance will not work.\",\n );\n }\n\n return descriptor.value;\n }\n\n return yield* instantiatePlugin(\n yield* pluginDescriptorLoader(descriptor, context),\n context,\n );\n}\n\nconst instantiatePlugin = makeWeakCache(function* (\n { value, options, dirname, alias, externalDependencies }: LoadedDescriptor,\n cache: CacheConfigurator,\n): Handler {\n const pluginObj = validatePluginObject(value);\n\n const plugin = {\n ...pluginObj,\n };\n if (plugin.visitor) {\n plugin.visitor = traverse.explode({\n ...plugin.visitor,\n });\n }\n\n if (plugin.inherits) {\n const inheritsDescriptor: UnloadedDescriptor = {\n name: undefined,\n alias: `${alias}$inherits`,\n value: plugin.inherits,\n options,\n dirname,\n };\n\n const inherits = yield* forwardAsync(loadPluginDescriptor, run => {\n // If the inherited plugin changes, reinstantiate this plugin.\n return cache.invalidate(data => run(inheritsDescriptor, data));\n });\n\n plugin.pre = chain(inherits.pre, plugin.pre);\n plugin.post = chain(inherits.post, plugin.post);\n plugin.manipulateOptions = chain(\n inherits.manipulateOptions,\n plugin.manipulateOptions,\n );\n plugin.visitor = traverse.visitors.merge([\n inherits.visitor || {},\n plugin.visitor || {},\n ]);\n\n if (inherits.externalDependencies.length > 0) {\n if (externalDependencies.length === 0) {\n externalDependencies = inherits.externalDependencies;\n } else {\n externalDependencies = freezeDeepArray([\n externalDependencies,\n inherits.externalDependencies,\n ]);\n }\n }\n }\n\n return new Plugin(plugin, options, alias, externalDependencies);\n});\n\nconst needsFilename = (val: unknown) => val && typeof val !== \"function\";\n\nconst validateIfOptionNeedsFilename = (\n options: ValidatedOptions,\n descriptor: UnloadedDescriptor,\n): void => {\n if (\n needsFilename(options.test) ||\n needsFilename(options.include) ||\n needsFilename(options.exclude)\n ) {\n const formattedPresetName = descriptor.name\n ? `\"${descriptor.name}\"`\n : \"/* your preset */\";\n throw new ConfigError(\n [\n `Preset ${formattedPresetName} requires a filename to be set when babel is called directly,`,\n `\\`\\`\\``,\n `babel.transformSync(code, { filename: 'file.ts', presets: [${formattedPresetName}] });`,\n `\\`\\`\\``,\n `See https://babeljs.io/docs/en/options#filename for more information.`,\n ].join(\"\\n\"),\n );\n }\n};\n\nconst validatePreset = (\n preset: PresetInstance,\n context: ConfigContext,\n descriptor: UnloadedDescriptor,\n): void => {\n if (!context.filename) {\n const { options } = preset;\n validateIfOptionNeedsFilename(options, descriptor);\n if (options.overrides) {\n options.overrides.forEach(overrideOptions =>\n validateIfOptionNeedsFilename(overrideOptions, descriptor),\n );\n }\n }\n};\n\n/**\n * Generate a config object that will act as the root of a new nested config.\n */\nfunction* loadPresetDescriptor(\n descriptor: UnloadedDescriptor,\n context: Context.FullPreset,\n): Handler<{\n chain: ConfigChain | null;\n externalDependencies: ReadonlyDeepArray;\n}> {\n const preset = instantiatePreset(\n yield* presetDescriptorLoader(descriptor, context),\n );\n validatePreset(preset, context, descriptor);\n return {\n chain: yield* buildPresetChain(preset, context),\n externalDependencies: preset.externalDependencies,\n };\n}\n\nconst instantiatePreset = makeWeakCacheSync(\n ({\n value,\n dirname,\n alias,\n externalDependencies,\n }: LoadedDescriptor): PresetInstance => {\n return {\n options: validate(\"preset\", value),\n alias,\n dirname,\n externalDependencies,\n };\n },\n);\n\nfunction chain(\n a: undefined | ((...args: Args) => void),\n b: undefined | ((...args: Args) => void),\n) {\n const fns = [a, b].filter(Boolean);\n if (fns.length <= 1) return fns[0];\n\n return function (this: unknown, ...args: unknown[]) {\n for (const fn of fns) {\n fn.apply(this, args);\n }\n };\n}\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;;AAEA;;AACA;;AACA;;AACA;;AACA;;AACA;;AAQA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;;AAEA;;AAKA;;AACA;;AAGA;;AAIA;;eAsBeA,UAAA,CAAQ,UAAUC,cAAV,CACrBC,SADqB,EAEW;EAAA;;EAChC,MAAMC,MAAM,GAAG,OAAO,IAAAC,gBAAA,EAAyBF,SAAzB,CAAtB;;EACA,IAAI,CAACC,MAAL,EAAa;IACX,OAAO,IAAP;EACD;;EACD,MAAM;IAAEE,OAAF;IAAWC,OAAX;IAAoBC;EAApB,IAAqCJ,MAA3C;;EAEA,IAAII,YAAY,KAAK,SAArB,EAAgC;IAC9B,OAAO,IAAP;EACD;;EAED,MAAMC,cAAc,GAAG,EAAvB;EAEA,MAAM;IAAEC,OAAF;IAAWC;EAAX,IAAuBL,OAA7B;;EAEA,IAAI,CAACI,OAAD,IAAY,CAACC,OAAjB,EAA0B;IACxB,MAAM,IAAIC,KAAJ,CAAU,+CAAV,CAAN;EACD;;EAED,MAAMC,aAAiC,qBAClCN,OADkC;IAErCO,OAAO,EAAER,OAAO,CAACQ;EAFoB,EAAvC;;EAKA,MAAMC,YAAY,GAAIC,IAAD,IAAsB;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;EACtC,OAAO;IACLlB,OAAO,EAAE,IAAAiH,iBAAA,EAAS,QAAT,EAAmBnD,KAAnB,CADJ;IAELE,KAFK;IAGLD,OAHK;IAIL7C;EAJK,CAAP;AAMD,CAbuB,CAA1B;;AAgBA,SAASgB,KAAT,CACEgF,CADF,EAEEC,CAFF,EAGE;EACA,MAAMC,GAAG,GAAG,CAACF,CAAD,EAAIC,CAAJ,EAAO5E,MAAP,CAAc8E,OAAd,CAAZ;EACA,IAAID,GAAG,CAAC3F,MAAJ,IAAc,CAAlB,EAAqB,OAAO2F,GAAG,CAAC,CAAD,CAAV;EAErB,OAAO,UAAyB,GAAGE,IAA5B,EAA6C;IAClD,KAAK,MAAMjE,EAAX,IAAiB+D,GAAjB,EAAsB;MACpB/D,EAAE,CAACkE,KAAH,CAAS,IAAT,EAAeD,IAAf;IACD;EACF,CAJD;AAKD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/helpers/config-api.js b/node_modules/@babel/core/lib/config/helpers/config-api.js new file mode 100644 index 0000000..8a65457 --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/config-api.js @@ -0,0 +1,109 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.makeConfigAPI = makeConfigAPI; +exports.makePluginAPI = makePluginAPI; +exports.makePresetAPI = makePresetAPI; + +function _semver() { + const data = require("semver"); + + _semver = function () { + return data; + }; + + return data; +} + +var _ = require("../../"); + +var _caching = require("../caching"); + +function makeConfigAPI(cache) { + const env = value => cache.using(data => { + if (typeof value === "undefined") return data.envName; + + if (typeof value === "function") { + return (0, _caching.assertSimpleType)(value(data.envName)); + } + + return (Array.isArray(value) ? value : [value]).some(entry => { + if (typeof entry !== "string") { + throw new Error("Unexpected non-string value"); + } + + return entry === data.envName; + }); + }); + + const caller = cb => cache.using(data => (0, _caching.assertSimpleType)(cb(data.caller))); + + return { + version: _.version, + cache: cache.simple(), + env, + async: () => false, + caller, + assertVersion + }; +} + +function makePresetAPI(cache, externalDependencies) { + const targets = () => JSON.parse(cache.using(data => JSON.stringify(data.targets))); + + const addExternalDependency = ref => { + externalDependencies.push(ref); + }; + + return Object.assign({}, makeConfigAPI(cache), { + targets, + addExternalDependency + }); +} + +function makePluginAPI(cache, externalDependencies) { + const assumption = name => cache.using(data => data.assumptions[name]); + + return Object.assign({}, makePresetAPI(cache, externalDependencies), { + assumption + }); +} + +function assertVersion(range) { + if (typeof range === "number") { + if (!Number.isInteger(range)) { + throw new Error("Expected string or integer value."); + } + + range = `^${range}.0.0-0`; + } + + if (typeof range !== "string") { + throw new Error("Expected string or integer value."); + } + + if (_semver().satisfies(_.version, range)) return; + const limit = Error.stackTraceLimit; + + if (typeof limit === "number" && limit < 25) { + Error.stackTraceLimit = 25; + } + + const err = new Error(`Requires Babel "${range}", but was loaded with "${_.version}". ` + `If you are sure you have a compatible version of @babel/core, ` + `it is likely that something in your build process is loading the ` + `wrong version. Inspect the stack trace of this error to look for ` + `the first entry that doesn't mention "@babel/core" or "babel-core" ` + `to see what is calling Babel.`); + + if (typeof limit === "number") { + Error.stackTraceLimit = limit; + } + + throw Object.assign(err, { + code: "BABEL_VERSION_UNSUPPORTED", + version: _.version, + range + }); +} + +0 && 0; + +//# sourceMappingURL=config-api.js.map diff --git a/node_modules/@babel/core/lib/config/helpers/config-api.js.map b/node_modules/@babel/core/lib/config/helpers/config-api.js.map new file mode 100644 index 0000000..0c64ee4 --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/config-api.js.map @@ -0,0 +1 @@ +{"version":3,"names":["makeConfigAPI","cache","env","value","using","data","envName","assertSimpleType","Array","isArray","some","entry","Error","caller","cb","version","coreVersion","simple","async","assertVersion","makePresetAPI","externalDependencies","targets","JSON","parse","stringify","addExternalDependency","ref","push","makePluginAPI","assumption","name","assumptions","range","Number","isInteger","semver","satisfies","limit","stackTraceLimit","err","Object","assign","code"],"sources":["../../../src/config/helpers/config-api.ts"],"sourcesContent":["import semver from \"semver\";\nimport type { Targets } from \"@babel/helper-compilation-targets\";\n\nimport { version as coreVersion } from \"../../\";\nimport { assertSimpleType } from \"../caching\";\nimport type {\n CacheConfigurator,\n SimpleCacheConfigurator,\n SimpleType,\n} from \"../caching\";\n\nimport type { AssumptionName, CallerMetadata } from \"../validation/options\";\n\nimport type * as Context from \"../cache-contexts\";\n\ntype EnvFunction = {\n (): string;\n (extractor: (babelEnv: string) => T): T;\n (envVar: string): boolean;\n (envVars: Array): boolean;\n};\n\ntype CallerFactory = (\n extractor: (callerMetadata: CallerMetadata | undefined) => unknown,\n) => SimpleType;\ntype TargetsFunction = () => Targets;\ntype AssumptionFunction = (name: AssumptionName) => boolean | undefined;\n\nexport type ConfigAPI = {\n version: string;\n cache: SimpleCacheConfigurator;\n env: EnvFunction;\n async: () => boolean;\n assertVersion: typeof assertVersion;\n caller?: CallerFactory;\n};\n\nexport type PresetAPI = {\n targets: TargetsFunction;\n addExternalDependency: (ref: string) => void;\n} & ConfigAPI;\n\nexport type PluginAPI = {\n assumption: AssumptionFunction;\n} & PresetAPI;\n\nexport function makeConfigAPI(\n cache: CacheConfigurator,\n): ConfigAPI {\n // TODO(@nicolo-ribaudo): If we remove the explicit type from `value`\n // and the `as any` type cast, TypeScript crashes in an infinite\n // recursion. After upgrading to TS4.7 and finishing the noImplicitAny\n // PR, we should check if it still crashes and report it to the TS team.\n const env: EnvFunction = ((\n value: string | string[] | ((babelEnv: string) => T),\n ) =>\n cache.using(data => {\n if (typeof value === \"undefined\") return data.envName;\n if (typeof value === \"function\") {\n return assertSimpleType(value(data.envName));\n }\n return (Array.isArray(value) ? value : [value]).some(entry => {\n if (typeof entry !== \"string\") {\n throw new Error(\"Unexpected non-string value\");\n }\n return entry === data.envName;\n });\n })) as any;\n\n const caller = (cb: {\n (CallerMetadata: CallerMetadata | undefined): SimpleType;\n }) => cache.using(data => assertSimpleType(cb(data.caller)));\n\n return {\n version: coreVersion,\n cache: cache.simple(),\n // Expose \".env()\" so people can easily get the same env that we expose using the \"env\" key.\n env,\n async: () => false,\n caller,\n assertVersion,\n };\n}\n\nexport function makePresetAPI(\n cache: CacheConfigurator,\n externalDependencies: Array,\n): PresetAPI {\n const targets = () =>\n // We are using JSON.parse/JSON.stringify because it's only possible to cache\n // primitive values. We can safely stringify the targets object because it\n // only contains strings as its properties.\n // Please make the Record and Tuple proposal happen!\n JSON.parse(cache.using(data => JSON.stringify(data.targets)));\n\n const addExternalDependency = (ref: string) => {\n externalDependencies.push(ref);\n };\n\n return { ...makeConfigAPI(cache), targets, addExternalDependency };\n}\n\nexport function makePluginAPI(\n cache: CacheConfigurator,\n externalDependencies: Array,\n): PluginAPI {\n const assumption = (name: string) =>\n cache.using(data => data.assumptions[name]);\n\n return { ...makePresetAPI(cache, externalDependencies), assumption };\n}\n\nfunction assertVersion(range: string | number): void {\n if (typeof range === \"number\") {\n if (!Number.isInteger(range)) {\n throw new Error(\"Expected string or integer value.\");\n }\n range = `^${range}.0.0-0`;\n }\n if (typeof range !== \"string\") {\n throw new Error(\"Expected string or integer value.\");\n }\n\n if (semver.satisfies(coreVersion, range)) return;\n\n const limit = Error.stackTraceLimit;\n\n if (typeof limit === \"number\" && limit < 25) {\n // Bump up the limit if needed so that users are more likely\n // to be able to see what is calling Babel.\n Error.stackTraceLimit = 25;\n }\n\n const err = new Error(\n `Requires Babel \"${range}\", but was loaded with \"${coreVersion}\". ` +\n `If you are sure you have a compatible version of @babel/core, ` +\n `it is likely that something in your build process is loading the ` +\n `wrong version. Inspect the stack trace of this error to look for ` +\n `the first entry that doesn't mention \"@babel/core\" or \"babel-core\" ` +\n `to see what is calling Babel.`,\n );\n\n if (typeof limit === \"number\") {\n Error.stackTraceLimit = limit;\n }\n\n throw Object.assign(err, {\n code: \"BABEL_VERSION_UNSUPPORTED\",\n version: coreVersion,\n range,\n });\n}\n"],"mappings":";;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAGA;;AACA;;AA0CO,SAASA,aAAT,CACLC,KADK,EAEM;EAKX,M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,EAAE,2BADiB;IAEvB5B,OAAO,EAAEC,SAFc;IAGvBiB;EAHuB,CAAnB,CAAN;AAKD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/helpers/deep-array.js b/node_modules/@babel/core/lib/config/helpers/deep-array.js new file mode 100644 index 0000000..80cc2d0 --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/deep-array.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.finalize = finalize; +exports.flattenToSet = flattenToSet; + +function finalize(deepArr) { + return Object.freeze(deepArr); +} + +function flattenToSet(arr) { + const result = new Set(); + const stack = [arr]; + + while (stack.length > 0) { + for (const el of stack.pop()) { + if (Array.isArray(el)) stack.push(el);else result.add(el); + } + } + + return result; +} + +0 && 0; + +//# sourceMappingURL=deep-array.js.map diff --git a/node_modules/@babel/core/lib/config/helpers/deep-array.js.map b/node_modules/@babel/core/lib/config/helpers/deep-array.js.map new file mode 100644 index 0000000..dcaf801 --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/deep-array.js.map @@ -0,0 +1 @@ +{"version":3,"names":["finalize","deepArr","Object","freeze","flattenToSet","arr","result","Set","stack","length","el","pop","Array","isArray","push","add"],"sources":["../../../src/config/helpers/deep-array.ts"],"sourcesContent":["export type DeepArray = Array>;\n\n// Just to make sure that DeepArray is not assignable to ReadonlyDeepArray\ndeclare const __marker: unique symbol;\nexport type ReadonlyDeepArray = ReadonlyArray> & {\n [__marker]: true;\n};\n\nexport function finalize(deepArr: DeepArray): ReadonlyDeepArray {\n return Object.freeze(deepArr) as ReadonlyDeepArray;\n}\n\nexport function flattenToSet(\n arr: ReadonlyDeepArray,\n): Set {\n const result = new Set();\n const stack = [arr];\n while (stack.length > 0) {\n for (const el of stack.pop()) {\n if (Array.isArray(el)) stack.push(el as ReadonlyDeepArray);\n else result.add(el as T);\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;AAQO,SAASA,QAAT,CAAqBC,OAArB,EAAkE;EACvE,OAAOC,MAAM,CAACC,MAAP,CAAcF,OAAd,CAAP;AACD;;AAEM,SAASG,YAAT,CACLC,GADK,EAEG;EACR,MAAMC,MAAM,GAAG,IAAIC,GAAJ,EAAf;EACA,MAAMC,KAAK,GAAG,CAACH,GAAD,CAAd;;EACA,OAAOG,KAAK,CAACC,MAAN,GAAe,CAAtB,EAAyB;IACvB,KAAK,MAAMC,EAAX,IAAiBF,KAAK,CAACG,GAAN,EAAjB,EAA8B;MAC5B,IAAIC,KAAK,CAACC,OAAN,CAAcH,EAAd,CAAJ,EAAuBF,KAAK,CAACM,IAAN,CAAWJ,EAAX,EAAvB,KACKJ,MAAM,CAACS,GAAP,CAAWL,EAAX;IACN;EACF;;EACD,OAAOJ,MAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/helpers/environment.js b/node_modules/@babel/core/lib/config/helpers/environment.js new file mode 100644 index 0000000..c0c1caa --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/environment.js @@ -0,0 +1,14 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getEnv = getEnv; + +function getEnv(defaultValue = "development") { + return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue; +} + +0 && 0; + +//# sourceMappingURL=environment.js.map diff --git a/node_modules/@babel/core/lib/config/helpers/environment.js.map b/node_modules/@babel/core/lib/config/helpers/environment.js.map new file mode 100644 index 0000000..eeae387 --- /dev/null +++ b/node_modules/@babel/core/lib/config/helpers/environment.js.map @@ -0,0 +1 @@ +{"version":3,"names":["getEnv","defaultValue","process","env","BABEL_ENV","NODE_ENV"],"sources":["../../../src/config/helpers/environment.ts"],"sourcesContent":["export function getEnv(defaultValue: string = \"development\"): string {\n return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;\n}\n"],"mappings":";;;;;;;AAAO,SAASA,MAAT,CAAgBC,YAAoB,GAAG,aAAvC,EAA8D;EACnE,OAAOC,OAAO,CAACC,GAAR,CAAYC,SAAZ,IAAyBF,OAAO,CAACC,GAAR,CAAYE,QAArC,IAAiDJ,YAAxD;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/index.js b/node_modules/@babel/core/lib/config/index.js new file mode 100644 index 0000000..dbc1c87 --- /dev/null +++ b/node_modules/@babel/core/lib/config/index.js @@ -0,0 +1,85 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createConfigItem = createConfigItem; +exports.createConfigItemSync = exports.createConfigItemAsync = void 0; +Object.defineProperty(exports, "default", { + enumerable: true, + get: function () { + return _full.default; + } +}); +exports.loadPartialConfigSync = exports.loadPartialConfigAsync = exports.loadPartialConfig = exports.loadOptionsSync = exports.loadOptionsAsync = exports.loadOptions = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _full = require("./full"); + +var _partial = require("./partial"); + +var _item = require("./item"); + +const loadOptionsRunner = _gensync()(function* (opts) { + var _config$options; + + const config = yield* (0, _full.default)(opts); + return (_config$options = config == null ? void 0 : config.options) != null ? _config$options : null; +}); + +const createConfigItemRunner = _gensync()(_item.createConfigItem); + +const maybeErrback = runner => (argOrCallback, maybeCallback) => { + let arg; + let callback; + + if (maybeCallback === undefined && typeof argOrCallback === "function") { + callback = argOrCallback; + arg = undefined; + } else { + callback = maybeCallback; + arg = argOrCallback; + } + + return callback ? runner.errback(arg, callback) : runner.sync(arg); +}; + +const loadPartialConfig = maybeErrback(_partial.loadPartialConfig); +exports.loadPartialConfig = loadPartialConfig; +const loadPartialConfigSync = _partial.loadPartialConfig.sync; +exports.loadPartialConfigSync = loadPartialConfigSync; +const loadPartialConfigAsync = _partial.loadPartialConfig.async; +exports.loadPartialConfigAsync = loadPartialConfigAsync; +const loadOptions = maybeErrback(loadOptionsRunner); +exports.loadOptions = loadOptions; +const loadOptionsSync = loadOptionsRunner.sync; +exports.loadOptionsSync = loadOptionsSync; +const loadOptionsAsync = loadOptionsRunner.async; +exports.loadOptionsAsync = loadOptionsAsync; +const createConfigItemSync = createConfigItemRunner.sync; +exports.createConfigItemSync = createConfigItemSync; +const createConfigItemAsync = createConfigItemRunner.async; +exports.createConfigItemAsync = createConfigItemAsync; + +function createConfigItem(target, options, callback) { + if (callback !== undefined) { + return createConfigItemRunner.errback(target, options, callback); + } else if (typeof options === "function") { + return createConfigItemRunner.errback(target, undefined, callback); + } else { + return createConfigItemRunner.sync(target, options); + } +} + +0 && 0; + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/core/lib/config/index.js.map b/node_modules/@babel/core/lib/config/index.js.map new file mode 100644 index 0000000..4b8d9ca --- /dev/null +++ b/node_modules/@babel/core/lib/config/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["loadOptionsRunner","gensync","opts","config","loadFullConfig","options","createConfigItemRunner","createConfigItemImpl","maybeErrback","runner","argOrCallback","maybeCallback","arg","callback","undefined","errback","sync","loadPartialConfig","loadPartialConfigRunner","loadPartialConfigSync","loadPartialConfigAsync","async","loadOptions","loadOptionsSync","loadOptionsAsync","createConfigItemSync","createConfigItemAsync","createConfigItem","target"],"sources":["../../src/config/index.ts"],"sourcesContent":["import gensync, { type Handler, type Callback } from \"gensync\";\n\nexport type {\n ResolvedConfig,\n InputOptions,\n PluginPasses,\n Plugin,\n} from \"./full\";\n\nimport type { PluginTarget } from \"./validation/options\";\n\nimport type {\n PluginAPI as basePluginAPI,\n PresetAPI as basePresetAPI,\n} from \"./helpers/config-api\";\nexport type { PluginObject } from \"./validation/plugins\";\ntype PluginAPI = basePluginAPI & typeof import(\"..\");\ntype PresetAPI = basePresetAPI & typeof import(\"..\");\nexport type { PluginAPI, PresetAPI };\n// todo: may need to refine PresetObject to be a subset of ValidatedOptions\nexport type {\n CallerMetadata,\n ValidatedOptions as PresetObject,\n} from \"./validation/options\";\n\nimport loadFullConfig, { type ResolvedConfig } from \"./full\";\nimport { loadPartialConfig as loadPartialConfigRunner } from \"./partial\";\n\nexport { loadFullConfig as default };\nexport type { PartialConfig } from \"./partial\";\n\nimport { createConfigItem as createConfigItemImpl } from \"./item\";\nimport type { ConfigItem } from \"./item\";\n\nconst loadOptionsRunner = gensync(function* (\n opts: unknown,\n): Handler {\n const config = yield* loadFullConfig(opts);\n // NOTE: We want to return \"null\" explicitly, while ?. alone returns undefined\n return config?.options ?? null;\n});\n\nconst createConfigItemRunner = gensync(createConfigItemImpl);\n\nconst maybeErrback =\n (runner: gensync.Gensync<[Arg], Return>) =>\n (argOrCallback: Arg | Callback, maybeCallback?: Callback) => {\n let arg: Arg | undefined;\n let callback: Callback;\n if (maybeCallback === undefined && typeof argOrCallback === \"function\") {\n callback = argOrCallback as Callback;\n arg = undefined;\n } else {\n callback = maybeCallback;\n arg = argOrCallback as Arg;\n }\n return callback ? runner.errback(arg, callback) : runner.sync(arg);\n };\n\nexport const loadPartialConfig = maybeErrback(loadPartialConfigRunner);\nexport const loadPartialConfigSync = loadPartialConfigRunner.sync;\nexport const loadPartialConfigAsync = loadPartialConfigRunner.async;\n\nexport const loadOptions = maybeErrback(loadOptionsRunner);\nexport const loadOptionsSync = loadOptionsRunner.sync;\nexport const loadOptionsAsync = loadOptionsRunner.async;\n\nexport const createConfigItemSync = createConfigItemRunner.sync;\nexport const createConfigItemAsync = createConfigItemRunner.async;\nexport function createConfigItem(\n target: PluginTarget,\n options: Parameters[1],\n callback?: (err: Error, val: ConfigItem | null) => void,\n) {\n if (callback !== undefined) {\n return createConfigItemRunner.errback(target, options, callback);\n } else if (typeof options === \"function\") {\n return createConfigItemRunner.errback(target, undefined, callback);\n } else {\n return createConfigItemRunner.sync(target, options);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAyBA;;AACA;;AAKA;;AAGA,MAAMA,iBAAiB,GAAGC,UAAA,CAAQ,WAChCC,IADgC,EAEA;EAAA;;EAChC,MAAMC,MAAM,GAAG,OAAO,IAAAC,aAAA,EAAeF,IAAf,CAAtB;EAEA,0B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,OAAOR,OAAP,KAAmB,UAAvB,EAAmC;IACxC,OAAOC,sBAAsB,CAACS,OAAvB,CAA+Ba,MAA/B,EAAuCd,SAAvC,EAAkDD,QAAlD,CAAP;EACD,CAFM,MAEA;IACL,OAAOP,sBAAsB,CAACU,IAAvB,CAA4BY,MAA5B,EAAoCvB,OAApC,CAAP;EACD;AACF"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/item.js b/node_modules/@babel/core/lib/config/item.js new file mode 100644 index 0000000..2620ad3 --- /dev/null +++ b/node_modules/@babel/core/lib/config/item.js @@ -0,0 +1,79 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createConfigItem = createConfigItem; +exports.createItemFromDescriptor = createItemFromDescriptor; +exports.getItemDescriptor = getItemDescriptor; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +var _configDescriptors = require("./config-descriptors"); + +function createItemFromDescriptor(desc) { + return new ConfigItem(desc); +} + +function* createConfigItem(value, { + dirname = ".", + type +} = {}) { + const descriptor = yield* (0, _configDescriptors.createDescriptor)(value, _path().resolve(dirname), { + type, + alias: "programmatic item" + }); + return createItemFromDescriptor(descriptor); +} + +function getItemDescriptor(item) { + if (item != null && item[CONFIG_ITEM_BRAND]) { + return item._descriptor; + } + + return undefined; +} + +const CONFIG_ITEM_BRAND = Symbol.for("@babel/core@7 - ConfigItem"); + +class ConfigItem { + constructor(descriptor) { + this._descriptor = void 0; + this[CONFIG_ITEM_BRAND] = true; + this.value = void 0; + this.options = void 0; + this.dirname = void 0; + this.name = void 0; + this.file = void 0; + this._descriptor = descriptor; + Object.defineProperty(this, "_descriptor", { + enumerable: false + }); + Object.defineProperty(this, CONFIG_ITEM_BRAND, { + enumerable: false + }); + this.value = this._descriptor.value; + this.options = this._descriptor.options; + this.dirname = this._descriptor.dirname; + this.name = this._descriptor.name; + this.file = this._descriptor.file ? { + request: this._descriptor.file.request, + resolved: this._descriptor.file.resolved + } : undefined; + Object.freeze(this); + } + +} + +Object.freeze(ConfigItem.prototype); +0 && 0; + +//# sourceMappingURL=item.js.map diff --git a/node_modules/@babel/core/lib/config/item.js.map b/node_modules/@babel/core/lib/config/item.js.map new file mode 100644 index 0000000..519fc98 --- /dev/null +++ b/node_modules/@babel/core/lib/config/item.js.map @@ -0,0 +1 @@ +{"version":3,"names":["createItemFromDescriptor","desc","ConfigItem","createConfigItem","value","dirname","type","descriptor","createDescriptor","path","resolve","alias","getItemDescriptor","item","CONFIG_ITEM_BRAND","_descriptor","undefined","Symbol","for","constructor","options","name","file","Object","defineProperty","enumerable","request","resolved","freeze","prototype"],"sources":["../../src/config/item.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\nimport type { PluginTarget, PluginOptions } from \"./validation/options\";\n\nimport path from \"path\";\nimport { createDescriptor } from \"./config-descriptors\";\n\nimport type { UnloadedDescriptor } from \"./config-descriptors\";\n\nexport function createItemFromDescriptor(desc: UnloadedDescriptor): ConfigItem {\n return new ConfigItem(desc);\n}\n\n/**\n * Create a config item using the same value format used in Babel's config\n * files. Items returned from this function should be cached by the caller\n * ideally, as recreating the config item will mean re-resolving the item\n * and re-evaluating the plugin/preset function.\n */\nexport function* createConfigItem(\n value:\n | PluginTarget\n | [PluginTarget, PluginOptions]\n | [PluginTarget, PluginOptions, string | void],\n {\n dirname = \".\",\n type,\n }: {\n dirname?: string;\n type?: \"preset\" | \"plugin\";\n } = {},\n): Handler {\n const descriptor = yield* createDescriptor(value, path.resolve(dirname), {\n type,\n alias: \"programmatic item\",\n });\n\n return createItemFromDescriptor(descriptor);\n}\n\nexport function getItemDescriptor(item: unknown): UnloadedDescriptor | void {\n if ((item as any)?.[CONFIG_ITEM_BRAND]) {\n return (item as ConfigItem)._descriptor;\n }\n\n return undefined;\n}\n\nexport type { ConfigItem };\n\nconst CONFIG_ITEM_BRAND = Symbol.for(\"@babel/core@7 - ConfigItem\");\n\n/**\n * A public representation of a plugin/preset that will _eventually_ be load.\n * Users can use this to interact with the results of a loaded Babel\n * configuration.\n *\n * Any changes to public properties of this class should be considered a\n * breaking change to Babel's API.\n */\nclass ConfigItem {\n /**\n * The private underlying descriptor that Babel actually cares about.\n * If you access this, you are a bad person.\n */\n _descriptor: UnloadedDescriptor;\n\n // TODO(Babel 8): Check if this symbol needs to be updated\n /**\n * Used to detect ConfigItem instances from other Babel instances.\n */\n [CONFIG_ITEM_BRAND] = true;\n\n /**\n * The resolved value of the item itself.\n */\n value: {} | Function;\n\n /**\n * The options, if any, that were passed to the item.\n * Mutating this will lead to undefined behavior.\n *\n * \"false\" means that this item has been disabled.\n */\n options: {} | void | false;\n\n /**\n * The directory that the options for this item are relative to.\n */\n dirname: string;\n\n /**\n * Get the name of the plugin, if the user gave it one.\n */\n name: string | void;\n\n /**\n * Data about the file that the item was loaded from, if Babel knows it.\n */\n file: {\n // The requested path, e.g. \"@babel/env\".\n request: string;\n // The resolved absolute path of the file.\n resolved: string;\n } | void;\n\n constructor(descriptor: UnloadedDescriptor) {\n // Make people less likely to stumble onto this if they are exploring\n // programmatically, and also make sure that if people happen to\n // pass the item through JSON.stringify, it doesn't show up.\n this._descriptor = descriptor;\n Object.defineProperty(this, \"_descriptor\", { enumerable: false });\n\n Object.defineProperty(this, CONFIG_ITEM_BRAND, { enumerable: false });\n\n this.value = this._descriptor.value;\n this.options = this._descriptor.options;\n this.dirname = this._descriptor.dirname;\n this.name = this._descriptor.name;\n this.file = this._descriptor.file\n ? {\n request: this._descriptor.file.request,\n resolved: this._descriptor.file.resolved,\n }\n : undefined;\n\n // Freeze the object to make it clear that people shouldn't expect mutating\n // this object to do anything. A new item should be created if they want\n // to change something.\n Object.freeze(this);\n }\n}\n\nObject.freeze(ConfigItem.prototype);\n"],"mappings":";;;;;;;;;AAGA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;;AAIO,SAASA,wBAAT,CAAkCC,IAAlC,EAAwE;EAC7E,OAAO,IAAIC,UAAJ,CAAeD,IAAf,CAAP;AACD;;AAQM,UAA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AA7B;IACA,KAAKC,IAAL,GAAY,KAAKP,WAAL,CAAiBO,IAAjB,GACR;MACEI,OAAO,EAAE,KAAKX,WAAL,CAAiBO,IAAjB,CAAsBI,OADjC;MAEEC,QAAQ,EAAE,KAAKZ,WAAL,CAAiBO,IAAjB,CAAsBK;IAFlC,CADQ,GAKRX,SALJ;IAUAO,MAAM,CAACK,MAAP,CAAc,IAAd;EACD;;AAtEc;;AAyEjBL,MAAM,CAACK,MAAP,CAAc1B,UAAU,CAAC2B,SAAzB"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/partial.js b/node_modules/@babel/core/lib/config/partial.js new file mode 100644 index 0000000..87b2c81 --- /dev/null +++ b/node_modules/@babel/core/lib/config/partial.js @@ -0,0 +1,200 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadPrivatePartialConfig; +exports.loadPartialConfig = void 0; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _plugin = require("./plugin"); + +var _util = require("./util"); + +var _item = require("./item"); + +var _configChain = require("./config-chain"); + +var _environment = require("./helpers/environment"); + +var _options = require("./validation/options"); + +var _files = require("./files"); + +var _resolveTargets = require("./resolve-targets"); + +const _excluded = ["showIgnoredFiles"]; + +function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } + +function resolveRootMode(rootDir, rootMode) { + switch (rootMode) { + case "root": + return rootDir; + + case "upward-optional": + { + const upwardRootDir = (0, _files.findConfigUpwards)(rootDir); + return upwardRootDir === null ? rootDir : upwardRootDir; + } + + case "upward": + { + const upwardRootDir = (0, _files.findConfigUpwards)(rootDir); + if (upwardRootDir !== null) return upwardRootDir; + throw Object.assign(new Error(`Babel was run with rootMode:"upward" but a root could not ` + `be found when searching upward from "${rootDir}".\n` + `One of the following config files must be in the directory tree: ` + `"${_files.ROOT_CONFIG_FILENAMES.join(", ")}".`), { + code: "BABEL_ROOT_NOT_FOUND", + dirname: rootDir + }); + } + + default: + throw new Error(`Assertion failure - unknown rootMode value.`); + } +} + +function* loadPrivatePartialConfig(inputOpts) { + if (inputOpts != null && (typeof inputOpts !== "object" || Array.isArray(inputOpts))) { + throw new Error("Babel options must be an object, null, or undefined"); + } + + const args = inputOpts ? (0, _options.validate)("arguments", inputOpts) : {}; + const { + envName = (0, _environment.getEnv)(), + cwd = ".", + root: rootDir = ".", + rootMode = "root", + caller, + cloneInputAst = true + } = args; + + const absoluteCwd = _path().resolve(cwd); + + const absoluteRootDir = resolveRootMode(_path().resolve(absoluteCwd, rootDir), rootMode); + const filename = typeof args.filename === "string" ? _path().resolve(cwd, args.filename) : undefined; + const showConfigPath = yield* (0, _files.resolveShowConfigPath)(absoluteCwd); + const context = { + filename, + cwd: absoluteCwd, + root: absoluteRootDir, + envName, + caller, + showConfig: showConfigPath === filename + }; + const configChain = yield* (0, _configChain.buildRootChain)(args, context); + if (!configChain) return null; + const merged = { + assumptions: {} + }; + configChain.options.forEach(opts => { + (0, _util.mergeOptions)(merged, opts); + }); + const options = Object.assign({}, merged, { + targets: (0, _resolveTargets.resolveTargets)(merged, absoluteRootDir), + cloneInputAst, + babelrc: false, + configFile: false, + browserslistConfigFile: false, + passPerPreset: false, + envName: context.envName, + cwd: context.cwd, + root: context.root, + rootMode: "root", + filename: typeof context.filename === "string" ? context.filename : undefined, + plugins: configChain.plugins.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor)), + presets: configChain.presets.map(descriptor => (0, _item.createItemFromDescriptor)(descriptor)) + }); + return { + options, + context, + fileHandling: configChain.fileHandling, + ignore: configChain.ignore, + babelrc: configChain.babelrc, + config: configChain.config, + files: configChain.files + }; +} + +const loadPartialConfig = _gensync()(function* (opts) { + let showIgnoredFiles = false; + + if (typeof opts === "object" && opts !== null && !Array.isArray(opts)) { + var _opts = opts; + ({ + showIgnoredFiles + } = _opts); + opts = _objectWithoutPropertiesLoose(_opts, _excluded); + _opts; + } + + const result = yield* loadPrivatePartialConfig(opts); + if (!result) return null; + const { + options, + babelrc, + ignore, + config, + fileHandling, + files + } = result; + + if (fileHandling === "ignored" && !showIgnoredFiles) { + return null; + } + + (options.plugins || []).forEach(item => { + if (item.value instanceof _plugin.default) { + throw new Error("Passing cached plugin instances is not supported in " + "babel.loadPartialConfig()"); + } + }); + return new PartialConfig(options, babelrc ? babelrc.filepath : undefined, ignore ? ignore.filepath : undefined, config ? config.filepath : undefined, fileHandling, files); +}); + +exports.loadPartialConfig = loadPartialConfig; + +class PartialConfig { + constructor(options, babelrc, ignore, config, fileHandling, files) { + this.options = void 0; + this.babelrc = void 0; + this.babelignore = void 0; + this.config = void 0; + this.fileHandling = void 0; + this.files = void 0; + this.options = options; + this.babelignore = ignore; + this.babelrc = babelrc; + this.config = config; + this.fileHandling = fileHandling; + this.files = files; + Object.freeze(this); + } + + hasFilesystemConfig() { + return this.babelrc !== undefined || this.config !== undefined; + } + +} + +Object.freeze(PartialConfig.prototype); +0 && 0; + +//# sourceMappingURL=partial.js.map diff --git a/node_modules/@babel/core/lib/config/partial.js.map b/node_modules/@babel/core/lib/config/partial.js.map new file mode 100644 index 0000000..b629107 --- /dev/null +++ b/node_modules/@babel/core/lib/config/partial.js.map @@ -0,0 +1 @@ +{"version":3,"names":["resolveRootMode","rootDir","rootMode","upwardRootDir","findConfigUpwards","Object","assign","Error","ROOT_CONFIG_FILENAMES","join","code","dirname","loadPrivatePartialConfig","inputOpts","Array","isArray","args","validate","envName","getEnv","cwd","root","caller","cloneInputAst","absoluteCwd","path","resolve","absoluteRootDir","filename","undefined","showConfigPath","resolveShowConfigPath","context","showConfig","configChain","buildRootChain","merged","assumptions","options","forEach","opts","mergeOptions","targets","resolveTargets","babelrc","configFile","browserslistConfigFile","passPerPreset","plugins","map","descriptor","createItemFromDescriptor","presets","fileHandling","ignore","config","files","loadPartialConfig","gensync","showIgnoredFiles","result","item","value","Plugin","PartialConfig","filepath","constructor","babelignore","freeze","hasFilesystemConfig","prototype"],"sources":["../../src/config/partial.ts"],"sourcesContent":["import path from \"path\";\nimport gensync from \"gensync\";\nimport type { Handler } from \"gensync\";\nimport Plugin from \"./plugin\";\nimport { mergeOptions } from \"./util\";\nimport { createItemFromDescriptor } from \"./item\";\nimport { buildRootChain } from \"./config-chain\";\nimport type { ConfigContext, FileHandling } from \"./config-chain\";\nimport { getEnv } from \"./helpers/environment\";\nimport { validate } from \"./validation/options\";\n\nimport type {\n ValidatedOptions,\n NormalizedOptions,\n RootMode,\n} from \"./validation/options\";\n\nimport {\n findConfigUpwards,\n resolveShowConfigPath,\n ROOT_CONFIG_FILENAMES,\n} from \"./files\";\nimport type { ConfigFile, IgnoreFile } from \"./files\";\nimport { resolveTargets } from \"./resolve-targets\";\n\nfunction resolveRootMode(rootDir: string, rootMode: RootMode): string {\n switch (rootMode) {\n case \"root\":\n return rootDir;\n\n case \"upward-optional\": {\n const upwardRootDir = findConfigUpwards(rootDir);\n return upwardRootDir === null ? rootDir : upwardRootDir;\n }\n\n case \"upward\": {\n const upwardRootDir = findConfigUpwards(rootDir);\n if (upwardRootDir !== null) return upwardRootDir;\n\n throw Object.assign(\n new Error(\n `Babel was run with rootMode:\"upward\" but a root could not ` +\n `be found when searching upward from \"${rootDir}\".\\n` +\n `One of the following config files must be in the directory tree: ` +\n `\"${ROOT_CONFIG_FILENAMES.join(\", \")}\".`,\n ) as any,\n {\n code: \"BABEL_ROOT_NOT_FOUND\",\n dirname: rootDir,\n },\n );\n }\n default:\n throw new Error(`Assertion failure - unknown rootMode value.`);\n }\n}\n\ntype PrivPartialConfig = {\n options: NormalizedOptions;\n context: ConfigContext;\n fileHandling: FileHandling;\n ignore: IgnoreFile | void;\n babelrc: ConfigFile | void;\n config: ConfigFile | void;\n files: Set;\n};\n\nexport default function* loadPrivatePartialConfig(\n inputOpts: unknown,\n): Handler {\n if (\n inputOpts != null &&\n (typeof inputOpts !== \"object\" || Array.isArray(inputOpts))\n ) {\n throw new Error(\"Babel options must be an object, null, or undefined\");\n }\n\n const args = inputOpts ? validate(\"arguments\", inputOpts) : {};\n\n const {\n envName = getEnv(),\n cwd = \".\",\n root: rootDir = \".\",\n rootMode = \"root\",\n caller,\n cloneInputAst = true,\n } = args;\n const absoluteCwd = path.resolve(cwd);\n const absoluteRootDir = resolveRootMode(\n path.resolve(absoluteCwd, rootDir),\n rootMode,\n );\n\n const filename =\n typeof args.filename === \"string\"\n ? path.resolve(cwd, args.filename)\n : undefined;\n\n const showConfigPath = yield* resolveShowConfigPath(absoluteCwd);\n\n const context: ConfigContext = {\n filename,\n cwd: absoluteCwd,\n root: absoluteRootDir,\n envName,\n caller,\n showConfig: showConfigPath === filename,\n };\n\n const configChain = yield* buildRootChain(args, context);\n if (!configChain) return null;\n\n const merged: ValidatedOptions = {\n assumptions: {},\n };\n configChain.options.forEach(opts => {\n mergeOptions(merged as any, opts);\n });\n\n const options: NormalizedOptions = {\n ...merged,\n targets: resolveTargets(merged, absoluteRootDir),\n\n // Tack the passes onto the object itself so that, if this object is\n // passed back to Babel a second time, it will be in the right structure\n // to not change behavior.\n cloneInputAst,\n babelrc: false,\n configFile: false,\n browserslistConfigFile: false,\n passPerPreset: false,\n envName: context.envName,\n cwd: context.cwd,\n root: context.root,\n rootMode: \"root\",\n filename:\n typeof context.filename === \"string\" ? context.filename : undefined,\n\n plugins: configChain.plugins.map(descriptor =>\n createItemFromDescriptor(descriptor),\n ),\n presets: configChain.presets.map(descriptor =>\n createItemFromDescriptor(descriptor),\n ),\n };\n\n return {\n options,\n context,\n fileHandling: configChain.fileHandling,\n ignore: configChain.ignore,\n babelrc: configChain.babelrc,\n config: configChain.config,\n files: configChain.files,\n };\n}\n\ntype LoadPartialConfigOpts = {\n showIgnoredFiles?: boolean;\n};\n\nexport const loadPartialConfig = gensync(function* (\n opts?: LoadPartialConfigOpts,\n): Handler {\n let showIgnoredFiles = false;\n // We only extract showIgnoredFiles if opts is an object, so that\n // loadPrivatePartialConfig can throw the appropriate error if it's not.\n if (typeof opts === \"object\" && opts !== null && !Array.isArray(opts)) {\n ({ showIgnoredFiles, ...opts } = opts);\n }\n\n const result: PrivPartialConfig | undefined | null =\n yield* loadPrivatePartialConfig(opts);\n if (!result) return null;\n\n const { options, babelrc, ignore, config, fileHandling, files } = result;\n\n if (fileHandling === \"ignored\" && !showIgnoredFiles) {\n return null;\n }\n\n (options.plugins || []).forEach(item => {\n // @ts-expect-error todo(flow->ts): better type annotation for `item.value`\n if (item.value instanceof Plugin) {\n throw new Error(\n \"Passing cached plugin instances is not supported in \" +\n \"babel.loadPartialConfig()\",\n );\n }\n });\n\n return new PartialConfig(\n options,\n babelrc ? babelrc.filepath : undefined,\n ignore ? ignore.filepath : undefined,\n config ? config.filepath : undefined,\n fileHandling,\n files,\n );\n});\n\nexport type { PartialConfig };\n\nclass PartialConfig {\n /**\n * These properties are public, so any changes to them should be considered\n * a breaking change to Babel's API.\n */\n options: NormalizedOptions;\n babelrc: string | void;\n babelignore: string | void;\n config: string | void;\n fileHandling: FileHandling;\n files: Set;\n\n constructor(\n options: NormalizedOptions,\n babelrc: string | void,\n ignore: string | void,\n config: string | void,\n fileHandling: FileHandling,\n files: Set,\n ) {\n this.options = options;\n this.babelignore = ignore;\n this.babelrc = babelrc;\n this.config = config;\n this.fileHandling = fileHandling;\n this.files = files;\n\n // Freeze since this is a public API and it should be extremely obvious that\n // reassigning properties on here does nothing.\n Object.freeze(this);\n }\n\n /**\n * Returns true if there is a config file in the filesystem for this config.\n */\n hasFilesystemConfig(): boolean {\n return this.babelrc !== undefined || this.config !== undefined;\n }\n}\nObject.freeze(PartialConfig.prototype);\n"],"mappings":";;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;;AACA;;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node_modules/@babel/core/lib/config/pattern-to-regex.js b/node_modules/@babel/core/lib/config/pattern-to-regex.js new file mode 100644 index 0000000..f4408a2 --- /dev/null +++ b/node_modules/@babel/core/lib/config/pattern-to-regex.js @@ -0,0 +1,48 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = pathToPattern; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +const sep = `\\${_path().sep}`; +const endSep = `(?:${sep}|$)`; +const substitution = `[^${sep}]+`; +const starPat = `(?:${substitution}${sep})`; +const starPatLast = `(?:${substitution}${endSep})`; +const starStarPat = `${starPat}*?`; +const starStarPatLast = `${starPat}*?${starPatLast}?`; + +function escapeRegExp(string) { + return string.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&"); +} + +function pathToPattern(pattern, dirname) { + const parts = _path().resolve(dirname, pattern).split(_path().sep); + + return new RegExp(["^", ...parts.map((part, i) => { + const last = i === parts.length - 1; + if (part === "**") return last ? starStarPatLast : starStarPat; + if (part === "*") return last ? starPatLast : starPat; + + if (part.indexOf("*.") === 0) { + return substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep); + } + + return escapeRegExp(part) + (last ? endSep : sep); + })].join("")); +} + +0 && 0; + +//# sourceMappingURL=pattern-to-regex.js.map diff --git a/node_modules/@babel/core/lib/config/pattern-to-regex.js.map b/node_modules/@babel/core/lib/config/pattern-to-regex.js.map new file mode 100644 index 0000000..ba99f47 --- /dev/null +++ b/node_modules/@babel/core/lib/config/pattern-to-regex.js.map @@ -0,0 +1 @@ +{"version":3,"names":["sep","path","endSep","substitution","starPat","starPatLast","starStarPat","starStarPatLast","escapeRegExp","string","replace","pathToPattern","pattern","dirname","parts","resolve","split","RegExp","map","part","i","last","length","indexOf","slice","join"],"sources":["../../src/config/pattern-to-regex.ts"],"sourcesContent":["import path from \"path\";\n\nconst sep = `\\\\${path.sep}`;\nconst endSep = `(?:${sep}|$)`;\n\nconst substitution = `[^${sep}]+`;\n\nconst starPat = `(?:${substitution}${sep})`;\nconst starPatLast = `(?:${substitution}${endSep})`;\n\nconst starStarPat = `${starPat}*?`;\nconst starStarPatLast = `${starPat}*?${starPatLast}?`;\n\nfunction escapeRegExp(string: string) {\n return string.replace(/[|\\\\{}()[\\]^$+*?.]/g, \"\\\\$&\");\n}\n\n/**\n * Implement basic pattern matching that will allow users to do the simple\n * tests with * and **. If users want full complex pattern matching, then can\n * always use regex matching, or function validation.\n */\nexport default function pathToPattern(\n pattern: string,\n dirname: string,\n): RegExp {\n const parts = path.resolve(dirname, pattern).split(path.sep);\n\n return new RegExp(\n [\n \"^\",\n ...parts.map((part, i) => {\n const last = i === parts.length - 1;\n\n // ** matches 0 or more path parts.\n if (part === \"**\") return last ? starStarPatLast : starStarPat;\n\n // * matches 1 path part.\n if (part === \"*\") return last ? starPatLast : starPat;\n\n // *.ext matches a wildcard with an extension.\n if (part.indexOf(\"*.\") === 0) {\n return (\n substitution + escapeRegExp(part.slice(1)) + (last ? endSep : sep)\n );\n }\n\n // Otherwise match the pattern text.\n return escapeRegExp(part) + (last ? endSep : sep);\n }),\n ].join(\"\"),\n );\n}\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA,MAAMA,GAAG,GAAI,KAAIC,OAAA,CAAKD,GAAI,EAA1B;AACA,MAAME,MAAM,GAAI,MAAKF,GAAI,KAAzB;AAEA,MAAMG,YAAY,GAAI,KAAIH,GAAI,IAA9B;AAEA,MAAMI,OAAO,GAAI,MAAKD,YAAa,GAAEH,GAAI,GAAzC;AACA,MAAMK,WAAW,GAAI,MAAKF,YAAa,GAAED,MAAO,GAAhD;AAEA,MAAMI,WAAW,GAAI,GAAEF,OAAQ,IAA/B;AACA,MAAMG,eAAe,GAAI,GAAEH,OAAQ,KAAIC,WAAY,GAAnD;;AAEA,SAASG,YAAT,CAAsBC,MAAtB,EAAsC;EACpC,OAAOA,MAAM,CAACC,OAAP,CAAe,qBAAf,EAAsC,MAAtC,CAAP;AACD;;AAOc,SAASC,aAAT,CACbC,OADa,EAEbC,OAFa,EAGL;EACR,MAAMC,KAAK,GAAGb,OAAA,CAAKc,OAAL,CAAaF,OAAb,EAAsBD,OAAtB,EAA+BI,KAA/B,CAAqCf,OAAA,CAAKD,GAA1C,CAAd;;EAEA,OAAO,IAAIiB,MAAJ,CACL,CACE,GADF,EAEE,GAAGH,KAAK,CAACI,GAAN,CAAU,CAACC,IAAD,EAAOC,CAAP,KAAa;IACxB,MAAMC,IAAI,GAAGD,CAAC,KAAKN,KAAK,CAACQ,MAAN,GAAe,CAAlC;IAGA,IAAIH,IAAI,KAAK,IAAb,EAAmB,OAAOE,IAAI,GAAGd,eAAH,GAAqBD,WAAhC;IAGnB,IAAIa,IAAI,KAAK,GAAb,EAAkB,OAAOE,IAAI,GAAGhB,WAAH,GAAiBD,OAA5B;;IAGlB,IAAIe,IAAI,CAACI,OAAL,CAAa,IAAb,MAAuB,CAA3B,EAA8B;MAC5B,OACEpB,YAAY,GAAGK,YAAY,CAACW,IAAI,CAACK,KAAL,CAAW,CAAX,CAAD,CAA3B,IAA8CH,IAAI,GAAGnB,MAAH,GAAYF,GAA9D,CADF;IAGD;;IAGD,OAAOQ,YAAY,CAACW,IAAD,CAAZ,IAAsBE,IAAI,GAAGnB,MAAH,GAAYF,GAAtC,CAAP;EACD,CAlBE,CAFL,EAqBEyB,IArBF,CAqBO,EArBP,CADK,CAAP;AAwBD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/plugin.js b/node_modules/@babel/core/lib/config/plugin.js new file mode 100644 index 0000000..cefb645 --- /dev/null +++ b/node_modules/@babel/core/lib/config/plugin.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _deepArray = require("./helpers/deep-array"); + +class Plugin { + constructor(plugin, options, key, externalDependencies = (0, _deepArray.finalize)([])) { + this.key = void 0; + this.manipulateOptions = void 0; + this.post = void 0; + this.pre = void 0; + this.visitor = void 0; + this.parserOverride = void 0; + this.generatorOverride = void 0; + this.options = void 0; + this.externalDependencies = void 0; + this.key = plugin.name || key; + this.manipulateOptions = plugin.manipulateOptions; + this.post = plugin.post; + this.pre = plugin.pre; + this.visitor = plugin.visitor || {}; + this.parserOverride = plugin.parserOverride; + this.generatorOverride = plugin.generatorOverride; + this.options = options; + this.externalDependencies = externalDependencies; + } + +} + +exports.default = Plugin; +0 && 0; + +//# sourceMappingURL=plugin.js.map diff --git a/node_modules/@babel/core/lib/config/plugin.js.map b/node_modules/@babel/core/lib/config/plugin.js.map new file mode 100644 index 0000000..92acd71 --- /dev/null +++ b/node_modules/@babel/core/lib/config/plugin.js.map @@ -0,0 +1 @@ +{"version":3,"names":["Plugin","constructor","plugin","options","key","externalDependencies","finalize","manipulateOptions","post","pre","visitor","parserOverride","generatorOverride","name"],"sources":["../../src/config/plugin.ts"],"sourcesContent":["import { finalize } from \"./helpers/deep-array\";\nimport type { ReadonlyDeepArray } from \"./helpers/deep-array\";\nimport type { PluginObject } from \"./validation/plugins\";\n\nexport default class Plugin {\n key: string | undefined | null;\n manipulateOptions?: (options: unknown, parserOpts: unknown) => void;\n post?: PluginObject[\"post\"];\n pre?: PluginObject[\"pre\"];\n visitor: PluginObject[\"visitor\"];\n\n parserOverride?: Function;\n generatorOverride?: Function;\n\n options: {};\n\n externalDependencies: ReadonlyDeepArray;\n\n constructor(\n plugin: PluginObject,\n options: {},\n key?: string,\n externalDependencies: ReadonlyDeepArray = finalize([]),\n ) {\n this.key = plugin.name || key;\n\n this.manipulateOptions = plugin.manipulateOptions;\n this.post = plugin.post;\n this.pre = plugin.pre;\n this.visitor = plugin.visitor || {};\n this.parserOverride = plugin.parserOverride;\n this.generatorOverride = plugin.generatorOverride;\n\n this.options = options;\n this.externalDependencies = externalDependencies;\n }\n}\n"],"mappings":";;;;;;;AAAA;;AAIe,MAAMA,MAAN,CAAa;EAc1BC,WAAW,CACTC,MADS,EAETC,OAFS,EAGTC,GAHS,EAITC,oBAA+C,GAAG,IAAAC,mBAAA,EAAS,EAAT,CAJzC,EAKT;IAAA,KAlBFF,GAkBE;IAAA,KAjBFG,iBAiBE;IAAA,KAhBFC,IAgBE;IAAA,KAfFC,GAeE;IAAA,KAdFC,OAcE;IAAA,KAZFC,cAYE;IAAA,KAXFC,iBAWE;IAAA,KATFT,OASE;IAAA,KAPFE,oBAOE;IACA,KAAKD,GAAL,GAAWF,MAAM,CAACW,IAAP,IAAeT,GAA1B;IAEA,KAAKG,iBAAL,GAAyBL,MAAM,CAACK,iBAAhC;IACA,KAAKC,IAAL,GAAYN,MAAM,CAACM,IAAnB;IACA,KAAKC,GAAL,GAAWP,MAAM,CAACO,GAAlB;IACA,KAAKC,OAAL,GAAeR,MAAM,CAACQ,OAAP,IAAkB,EAAjC;IACA,KAAKC,cAAL,GAAsBT,MAAM,CAACS,cAA7B;IACA,KAAKC,iBAAL,GAAyBV,MAAM,CAACU,iBAAhC;IAEA,KAAKT,OAAL,GAAeA,OAAf;IACA,KAAKE,oBAAL,GAA4BA,oBAA5B;EACD;;AA/ByB"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/printer.js b/node_modules/@babel/core/lib/config/printer.js new file mode 100644 index 0000000..58c97ac --- /dev/null +++ b/node_modules/@babel/core/lib/config/printer.js @@ -0,0 +1,142 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ConfigPrinter = exports.ChainFormatter = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +const ChainFormatter = { + Programmatic: 0, + Config: 1 +}; +exports.ChainFormatter = ChainFormatter; +const Formatter = { + title(type, callerName, filepath) { + let title = ""; + + if (type === ChainFormatter.Programmatic) { + title = "programmatic options"; + + if (callerName) { + title += " from " + callerName; + } + } else { + title = "config " + filepath; + } + + return title; + }, + + loc(index, envName) { + let loc = ""; + + if (index != null) { + loc += `.overrides[${index}]`; + } + + if (envName != null) { + loc += `.env["${envName}"]`; + } + + return loc; + }, + + *optionsAndDescriptors(opt) { + const content = Object.assign({}, opt.options); + delete content.overrides; + delete content.env; + const pluginDescriptors = [...(yield* opt.plugins())]; + + if (pluginDescriptors.length) { + content.plugins = pluginDescriptors.map(d => descriptorToConfig(d)); + } + + const presetDescriptors = [...(yield* opt.presets())]; + + if (presetDescriptors.length) { + content.presets = [...presetDescriptors].map(d => descriptorToConfig(d)); + } + + return JSON.stringify(content, undefined, 2); + } + +}; + +function descriptorToConfig(d) { + var _d$file; + + let name = (_d$file = d.file) == null ? void 0 : _d$file.request; + + if (name == null) { + if (typeof d.value === "object") { + name = d.value; + } else if (typeof d.value === "function") { + name = `[Function: ${d.value.toString().slice(0, 50)} ... ]`; + } + } + + if (name == null) { + name = "[Unknown]"; + } + + if (d.options === undefined) { + return name; + } else if (d.name == null) { + return [name, d.options]; + } else { + return [name, d.options, d.name]; + } +} + +class ConfigPrinter { + constructor() { + this._stack = []; + } + + configure(enabled, type, { + callerName, + filepath + }) { + if (!enabled) return () => {}; + return (content, index, envName) => { + this._stack.push({ + type, + callerName, + filepath, + content, + index, + envName + }); + }; + } + + static *format(config) { + let title = Formatter.title(config.type, config.callerName, config.filepath); + const loc = Formatter.loc(config.index, config.envName); + if (loc) title += ` ${loc}`; + const content = yield* Formatter.optionsAndDescriptors(config.content); + return `${title}\n${content}`; + } + + *output() { + if (this._stack.length === 0) return ""; + const configs = yield* _gensync().all(this._stack.map(s => ConfigPrinter.format(s))); + return configs.join("\n\n"); + } + +} + +exports.ConfigPrinter = ConfigPrinter; +0 && 0; + +//# sourceMappingURL=printer.js.map diff --git a/node_modules/@babel/core/lib/config/printer.js.map b/node_modules/@babel/core/lib/config/printer.js.map new file mode 100644 index 0000000..10a7711 --- /dev/null +++ b/node_modules/@babel/core/lib/config/printer.js.map @@ -0,0 +1 @@ +{"version":3,"names":["ChainFormatter","Programmatic","Config","Formatter","title","type","callerName","filepath","loc","index","envName","optionsAndDescriptors","opt","content","options","overrides","env","pluginDescriptors","plugins","length","map","d","descriptorToConfig","presetDescriptors","presets","JSON","stringify","undefined","name","file","request","value","toString","slice","ConfigPrinter","_stack","configure","enabled","push","format","config","output","configs","gensync","all","s","join"],"sources":["../../src/config/printer.ts"],"sourcesContent":["import gensync from \"gensync\";\n\nimport type { Handler } from \"gensync\";\n\nimport type {\n OptionsAndDescriptors,\n UnloadedDescriptor,\n} from \"./config-descriptors\";\n\n// todo: Use flow enums when @babel/transform-flow-types supports it\nexport const ChainFormatter = {\n Programmatic: 0,\n Config: 1,\n};\n\ntype PrintableConfig = {\n content: OptionsAndDescriptors;\n type: typeof ChainFormatter[keyof typeof ChainFormatter];\n callerName: string | undefined | null;\n filepath: string | undefined | null;\n index: number | undefined | null;\n envName: string | undefined | null;\n};\n\nconst Formatter = {\n title(\n type: typeof ChainFormatter[keyof typeof ChainFormatter],\n callerName?: string | null,\n filepath?: string | null,\n ): string {\n let title = \"\";\n if (type === ChainFormatter.Programmatic) {\n title = \"programmatic options\";\n if (callerName) {\n title += \" from \" + callerName;\n }\n } else {\n title = \"config \" + filepath;\n }\n return title;\n },\n loc(index?: number | null, envName?: string | null): string {\n let loc = \"\";\n if (index != null) {\n loc += `.overrides[${index}]`;\n }\n if (envName != null) {\n loc += `.env[\"${envName}\"]`;\n }\n return loc;\n },\n\n *optionsAndDescriptors(opt: OptionsAndDescriptors) {\n const content = { ...opt.options };\n // overrides and env will be printed as separated config items\n delete content.overrides;\n delete content.env;\n // resolve to descriptors\n const pluginDescriptors = [...(yield* opt.plugins())];\n if (pluginDescriptors.length) {\n content.plugins = pluginDescriptors.map(d => descriptorToConfig(d));\n }\n const presetDescriptors = [...(yield* opt.presets())];\n if (presetDescriptors.length) {\n content.presets = [...presetDescriptors].map(d => descriptorToConfig(d));\n }\n return JSON.stringify(content, undefined, 2);\n },\n};\n\nfunction descriptorToConfig(\n d: UnloadedDescriptor,\n): string | {} | Array {\n let name = d.file?.request;\n if (name == null) {\n if (typeof d.value === \"object\") {\n name = d.value;\n } else if (typeof d.value === \"function\") {\n // If the unloaded descriptor is a function, i.e. `plugins: [ require(\"my-plugin\") ]`,\n // we print the first 50 characters of the function source code and hopefully we can see\n // `name: 'my-plugin'` in the source\n name = `[Function: ${d.value.toString().slice(0, 50)} ... ]`;\n }\n }\n if (name == null) {\n name = \"[Unknown]\";\n }\n if (d.options === undefined) {\n return name;\n } else if (d.name == null) {\n return [name, d.options];\n } else {\n return [name, d.options, d.name];\n }\n}\n\nexport class ConfigPrinter {\n _stack: Array = [];\n configure(\n enabled: boolean,\n type: typeof ChainFormatter[keyof typeof ChainFormatter],\n {\n callerName,\n filepath,\n }: {\n callerName?: string;\n filepath?: string;\n },\n ) {\n if (!enabled) return () => {};\n return (\n content: OptionsAndDescriptors,\n index?: number | null,\n envName?: string | null,\n ) => {\n this._stack.push({\n type,\n callerName,\n filepath,\n content,\n index,\n envName,\n });\n };\n }\n static *format(config: PrintableConfig): Handler {\n let title = Formatter.title(\n config.type,\n config.callerName,\n config.filepath,\n );\n const loc = Formatter.loc(config.index, config.envName);\n if (loc) title += ` ${loc}`;\n const content = yield* Formatter.optionsAndDescriptors(config.content);\n return `${title}\\n${content}`;\n }\n\n *output(): Handler {\n if (this._stack.length === 0) return \"\";\n const configs = yield* gensync.all(\n this._stack.map(s => ConfigPrinter.format(s)),\n );\n return configs.join(\"\\n\\n\");\n }\n}\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAUO,MAAMA,cAAc,GAAG;EAC5BC,YAAY,EAAE,CADc;EAE5BC,MAAM,EAAE;AAFoB,CAAvB;;AAcP,MAAMC,SAAS,GAAG;EAChBC,KAAK,CACHC,IADG,EAEHC,UAFG,EAGHC,QAHG,EAIK;IACR,IAAIH,KAAK,GAAG,EAAZ;;IACA,IAAIC,IAAI,KAAKL,cAAc,CAACC,YAA5B,EAA0C;MACxCG,KAAK,GAAG,sBAAR;;MACA,IAAIE,UAAJ,EAAgB;QACdF,KAAK,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VoC,MAAM,CAACnC,IADG,EAEVmC,MAAM,CAAClC,UAFG,EAGVkC,MAAM,CAACjC,QAHG,CAAZ;IAKA,MAAMC,GAAG,GAAGL,SAAS,CAACK,GAAV,CAAcgC,MAAM,CAAC/B,KAArB,EAA4B+B,MAAM,CAAC9B,OAAnC,CAAZ;IACA,IAAIF,GAAJ,EAASJ,KAAK,IAAK,IAAGI,GAAI,EAAjB;IACT,MAAMK,OAAO,GAAG,OAAOV,SAAS,CAACQ,qBAAV,CAAgC6B,MAAM,CAAC3B,OAAvC,CAAvB;IACA,OAAQ,GAAET,KAAM,KAAIS,OAAQ,EAA5B;EACD;;EAEM,CAAN4B,MAAM,GAAoB;IACzB,IAAI,KAAKN,MAAL,CAAYhB,MAAZ,KAAuB,CAA3B,EAA8B,OAAO,EAAP;IAC9B,MAAMuB,OAAO,GAAG,OAAOC,UAAA,CAAQC,GAAR,CACrB,KAAKT,MAAL,CAAYf,GAAZ,CAAgByB,CAAC,IAAIX,aAAa,CAACK,MAAd,CAAqBM,CAArB,CAArB,CADqB,CAAvB;IAGA,OAAOH,OAAO,CAACI,IAAR,CAAa,MAAb,CAAP;EACD;;AA/CwB"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/resolve-targets-browser.js b/node_modules/@babel/core/lib/config/resolve-targets-browser.js new file mode 100644 index 0000000..8a81905 --- /dev/null +++ b/node_modules/@babel/core/lib/config/resolve-targets-browser.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.resolveBrowserslistConfigFile = resolveBrowserslistConfigFile; +exports.resolveTargets = resolveTargets; + +function _helperCompilationTargets() { + const data = require("@babel/helper-compilation-targets"); + + _helperCompilationTargets = function () { + return data; + }; + + return data; +} + +function resolveBrowserslistConfigFile(browserslistConfigFile, configFilePath) { + return undefined; +} + +function resolveTargets(options, root) { + const optTargets = options.targets; + let targets; + + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { + browsers: optTargets + }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = Object.assign({}, optTargets, { + esmodules: "intersect" + }); + } else { + targets = optTargets; + } + } + + return (0, _helperCompilationTargets().default)(targets, { + ignoreBrowserslistConfig: true, + browserslistEnv: options.browserslistEnv + }); +} + +0 && 0; + +//# sourceMappingURL=resolve-targets-browser.js.map diff --git a/node_modules/@babel/core/lib/config/resolve-targets-browser.js.map b/node_modules/@babel/core/lib/config/resolve-targets-browser.js.map new file mode 100644 index 0000000..1e8a7e0 --- /dev/null +++ b/node_modules/@babel/core/lib/config/resolve-targets-browser.js.map @@ -0,0 +1 @@ +{"version":3,"names":["resolveBrowserslistConfigFile","browserslistConfigFile","configFilePath","undefined","resolveTargets","options","root","optTargets","targets","Array","isArray","browsers","esmodules","getTargets","ignoreBrowserslistConfig","browserslistEnv"],"sources":["../../src/config/resolve-targets-browser.ts"],"sourcesContent":["import type { ValidatedOptions } from \"./validation/options\";\nimport getTargets, {\n type InputTargets,\n} from \"@babel/helper-compilation-targets\";\n\nimport type { Targets } from \"@babel/helper-compilation-targets\";\n\nexport function resolveBrowserslistConfigFile(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n browserslistConfigFile: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n configFilePath: string,\n): string | void {\n return undefined;\n}\n\nexport function resolveTargets(\n options: ValidatedOptions,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n root: string,\n): Targets {\n const optTargets = options.targets;\n let targets: InputTargets;\n\n if (typeof optTargets === \"string\" || Array.isArray(optTargets)) {\n targets = { browsers: optTargets };\n } else if (optTargets) {\n if (\"esmodules\" in optTargets) {\n targets = { ...optTargets, esmodules: \"intersect\" };\n } else {\n // https://github.com/microsoft/TypeScript/issues/17002\n targets = optTargets as InputTargets;\n }\n }\n\n return getTargets(targets, {\n ignoreBrowserslistConfig: true,\n browserslistEnv: options.browserslistEnv,\n });\n}\n"],"mappings":";;;;;;;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAMO,SAASA,6BAAT,CAELC,sBAFK,EAILC,cAJK,EAKU;EACf,OAAOC,SAAP;AACD;;AAEM,SAASC,cAAT,CACLC,OADK,EAGLC,IAHK,EAII;EACT,MAAMC,UAAU,GAAGF,OAAO,CAACG,OAA3B;EACA,IAAIA,OAAJ;;EAEA,IAAI,OAAOD,UAAP,KAAsB,QAAtB,IAAkCE,KAAK,CAACC,OAAN,CAAcH,UAAd,CAAtC,EAAiE;IAC/DC,OAAO,GAAG;MAAEG,QAAQ,EAAEJ;IAAZ,CAAV;EACD,CAFD,MAEO,IAAIA,UAAJ,EAAgB;IACrB,IAAI,eAAeA,UAAnB,EAA+B;MAC7BC,OAAO,qBAAQD,UAAR;QAAoBK,SAAS,EAAE;MAA/B,EAAP;IACD,CAFD,MAEO;MAELJ,OAAO,GAAGD,UAAV;IACD;EACF;;EAED,OAAO,IAAAM,mCAAA,EAAWL,OAAX,EAAoB;IACzBM,wBAAwB,EAAE,IADD;IAEzBC,eAAe,EAAEV,OAAO,CAACU;EAFA,CAApB,CAAP;AAID"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/resolve-targets.js b/node_modules/@babel/core/lib/config/resolve-targets.js new file mode 100644 index 0000000..a08d3ab --- /dev/null +++ b/node_modules/@babel/core/lib/config/resolve-targets.js @@ -0,0 +1,75 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.resolveBrowserslistConfigFile = resolveBrowserslistConfigFile; +exports.resolveTargets = resolveTargets; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _helperCompilationTargets() { + const data = require("@babel/helper-compilation-targets"); + + _helperCompilationTargets = function () { + return data; + }; + + return data; +} + +({}); + +function resolveBrowserslistConfigFile(browserslistConfigFile, configFileDir) { + return _path().resolve(configFileDir, browserslistConfigFile); +} + +function resolveTargets(options, root) { + const optTargets = options.targets; + let targets; + + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { + browsers: optTargets + }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = Object.assign({}, optTargets, { + esmodules: "intersect" + }); + } else { + targets = optTargets; + } + } + + const { + browserslistConfigFile + } = options; + let configFile; + let ignoreBrowserslistConfig = false; + + if (typeof browserslistConfigFile === "string") { + configFile = browserslistConfigFile; + } else { + ignoreBrowserslistConfig = browserslistConfigFile === false; + } + + return (0, _helperCompilationTargets().default)(targets, { + ignoreBrowserslistConfig, + configFile, + configPath: root, + browserslistEnv: options.browserslistEnv + }); +} + +0 && 0; + +//# sourceMappingURL=resolve-targets.js.map diff --git a/node_modules/@babel/core/lib/config/resolve-targets.js.map b/node_modules/@babel/core/lib/config/resolve-targets.js.map new file mode 100644 index 0000000..e0b2f04 --- /dev/null +++ b/node_modules/@babel/core/lib/config/resolve-targets.js.map @@ -0,0 +1 @@ +{"version":3,"names":["resolveBrowserslistConfigFile","browserslistConfigFile","configFileDir","path","resolve","resolveTargets","options","root","optTargets","targets","Array","isArray","browsers","esmodules","configFile","ignoreBrowserslistConfig","getTargets","configPath","browserslistEnv"],"sources":["../../src/config/resolve-targets.ts"],"sourcesContent":["type browserType = typeof import(\"./resolve-targets-browser\");\ntype nodeType = typeof import(\"./resolve-targets\");\n\n// Kind of gross, but essentially asserting that the exports of this module are the same as the\n// exports of index-browser, since this file may be replaced at bundle time with index-browser.\n({} as any as browserType as nodeType);\n\nimport type { ValidatedOptions } from \"./validation/options\";\nimport path from \"path\";\nimport getTargets, {\n type InputTargets,\n} from \"@babel/helper-compilation-targets\";\n\nimport type { Targets } from \"@babel/helper-compilation-targets\";\n\nexport function resolveBrowserslistConfigFile(\n browserslistConfigFile: string,\n configFileDir: string,\n): string | undefined {\n return path.resolve(configFileDir, browserslistConfigFile);\n}\n\nexport function resolveTargets(\n options: ValidatedOptions,\n root: string,\n): Targets {\n const optTargets = options.targets;\n let targets: InputTargets;\n\n if (typeof optTargets === \"string\" || Array.isArray(optTargets)) {\n targets = { browsers: optTargets };\n } else if (optTargets) {\n if (\"esmodules\" in optTargets) {\n targets = { ...optTargets, esmodules: \"intersect\" };\n } else {\n // https://github.com/microsoft/TypeScript/issues/17002\n targets = optTargets as InputTargets;\n }\n }\n\n const { browserslistConfigFile } = options;\n let configFile;\n let ignoreBrowserslistConfig = false;\n if (typeof browserslistConfigFile === \"string\") {\n configFile = browserslistConfigFile;\n } else {\n ignoreBrowserslistConfig = browserslistConfigFile === false;\n }\n\n return getTargets(targets, {\n ignoreBrowserslistConfig,\n configFile,\n configPath: root,\n browserslistEnv: options.browserslistEnv,\n });\n}\n"],"mappings":";;;;;;;;AAQA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAJA,CAAC,EAAD;;AAUO,SAASA,6BAAT,CACLC,sBADK,EAELC,aAFK,EAGe;EACpB,OAAOC,OAAA,CAAKC,OAAL,CAAaF,aAAb,EAA4BD,sBAA5B,CAAP;AACD;;AAEM,SAASI,cAAT,CACLC,OADK,EAELC,IAFK,EAGI;EACT,MAAMC,UAAU,GAAGF,OAAO,CAACG,OAA3B;EACA,IAAIA,OAAJ;;EAEA,IAAI,OAAOD,UAAP,KAAsB,QAAtB,IAAkCE,KAAK,CAACC,OAAN,CAAcH,UAAd,CAAtC,EAAiE;IAC/DC,OAAO,GAAG;MAAEG,QAAQ,EAAEJ;IAAZ,CAAV;EACD,CAFD,MAEO,IAAIA,UAAJ,EAAgB;IACrB,IAAI,eAAeA,UAAnB,EAA+B;MAC7BC,OAAO,qBAAQD,UAAR;QAAoBK,SAAS,EAAE;MAA/B,EAAP;IACD,CAFD,MAEO;MAELJ,OAAO,GAAGD,UAAV;IACD;EACF;;EAED,MAAM;IAAEP;EAAF,IAA6BK,OAAnC;EACA,IAAIQ,UAAJ;EACA,IAAIC,wBAAwB,GAAG,KAA/B;;EACA,IAAI,OAAOd,sBAAP,KAAkC,QAAtC,EAAgD;IAC9Ca,UAAU,GAAGb,sBAAb;EACD,CAFD,MAEO;IACLc,wBAAwB,GAAGd,sBAAsB,KAAK,KAAtD;EACD;;EAED,OAAO,IAAAe,mCAAA,EAAWP,OAAX,EAAoB;IACzBM,wBADyB;IAEzBD,UAFyB;IAGzBG,UAAU,EAAEV,IAHa;IAIzBW,eAAe,EAAEZ,OAAO,CAACY;EAJA,CAApB,CAAP;AAMD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/util.js b/node_modules/@babel/core/lib/config/util.js new file mode 100644 index 0000000..0e039e9 --- /dev/null +++ b/node_modules/@babel/core/lib/config/util.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIterableIterator = isIterableIterator; +exports.mergeOptions = mergeOptions; + +function mergeOptions(target, source) { + for (const k of Object.keys(source)) { + if ((k === "parserOpts" || k === "generatorOpts" || k === "assumptions") && source[k]) { + const parserOpts = source[k]; + const targetObj = target[k] || (target[k] = {}); + mergeDefaultFields(targetObj, parserOpts); + } else { + const val = source[k]; + if (val !== undefined) target[k] = val; + } + } +} + +function mergeDefaultFields(target, source) { + for (const k of Object.keys(source)) { + const val = source[k]; + if (val !== undefined) target[k] = val; + } +} + +function isIterableIterator(value) { + return !!value && typeof value.next === "function" && typeof value[Symbol.iterator] === "function"; +} + +0 && 0; + +//# sourceMappingURL=util.js.map diff --git a/node_modules/@babel/core/lib/config/util.js.map b/node_modules/@babel/core/lib/config/util.js.map new file mode 100644 index 0000000..65ae59b --- /dev/null +++ b/node_modules/@babel/core/lib/config/util.js.map @@ -0,0 +1 @@ +{"version":3,"names":["mergeOptions","target","source","k","Object","keys","parserOpts","targetObj","mergeDefaultFields","val","undefined","isIterableIterator","value","next","Symbol","iterator"],"sources":["../../src/config/util.ts"],"sourcesContent":["import type { ValidatedOptions, NormalizedOptions } from \"./validation/options\";\n\nexport function mergeOptions(\n target: ValidatedOptions,\n source: ValidatedOptions | NormalizedOptions,\n): void {\n for (const k of Object.keys(source)) {\n if (\n (k === \"parserOpts\" || k === \"generatorOpts\" || k === \"assumptions\") &&\n source[k]\n ) {\n const parserOpts = source[k];\n const targetObj = target[k] || (target[k] = {});\n mergeDefaultFields(targetObj, parserOpts);\n } else {\n //@ts-expect-error k must index source\n const val = source[k];\n //@ts-expect-error assigning source to target\n if (val !== undefined) target[k] = val as any;\n }\n }\n}\n\nfunction mergeDefaultFields(target: T, source: T) {\n for (const k of Object.keys(source) as (keyof T)[]) {\n const val = source[k];\n if (val !== undefined) target[k] = val;\n }\n}\n\nexport function isIterableIterator(value: any): value is IterableIterator {\n return (\n !!value &&\n typeof value.next === \"function\" &&\n typeof value[Symbol.iterator] === \"function\"\n );\n}\n"],"mappings":";;;;;;;;AAEO,SAASA,YAAT,CACLC,MADK,EAELC,MAFK,EAGC;EACN,KAAK,MAAMC,CAAX,IAAgBC,MAAM,CAACC,IAAP,CAAYH,MAAZ,CAAhB,EAAqC;IACnC,IACE,CAACC,CAAC,KAAK,YAAN,IAAsBA,CAAC,KAAK,eAA5B,IAA+CA,CAAC,KAAK,aAAtD,KACAD,MAAM,CAACC,CAAD,CAFR,EAGE;MACA,MAAMG,UAAU,GAAGJ,MAAM,CAACC,CAAD,CAAzB;MACA,MAAMI,SAAS,GAAGN,MAAM,CAACE,CAAD,CAAN,KAAcF,MAAM,CAACE,CAAD,CAAN,GAAY,EAA1B,CAAlB;MACAK,kBAAkB,CAACD,SAAD,EAAYD,UAAZ,CAAlB;IACD,CAPD,MAOO;MAEL,MAAMG,GAAG,GAAGP,MAAM,CAACC,CAAD,CAAlB;MAEA,IAAIM,GAAG,KAAKC,SAAZ,EAAuBT,MAAM,CAACE,CAAD,CAAN,GAAYM,GAAZ;IACxB;EACF;AACF;;AAED,SAASD,kBAAT,CAA0CP,MAA1C,EAAqDC,MAArD,EAAgE;EAC9D,KAAK,MAAMC,CAAX,IAAgBC,MAAM,CAACC,IAAP,CAAYH,MAAZ,CAAhB,EAAoD;IAClD,MAAMO,GAAG,GAAGP,MAAM,CAACC,CAAD,CAAlB;IACA,IAAIM,GAAG,KAAKC,SAAZ,EAAuBT,MAAM,CAACE,CAAD,CAAN,GAAYM,GAAZ;EACxB;AACF;;AAEM,SAASE,kBAAT,CAA4BC,KAA5B,EAAwE;EAC7E,OACE,CAAC,CAACA,KAAF,IACA,OAAOA,KAAK,CAACC,IAAb,KAAsB,UADtB,IAEA,OAAOD,KAAK,CAACE,MAAM,CAACC,QAAR,CAAZ,KAAkC,UAHpC;AAKD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/validation/option-assertions.js b/node_modules/@babel/core/lib/config/validation/option-assertions.js new file mode 100644 index 0000000..cdd5237 --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/option-assertions.js @@ -0,0 +1,356 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.access = access; +exports.assertArray = assertArray; +exports.assertAssumptions = assertAssumptions; +exports.assertBabelrcSearch = assertBabelrcSearch; +exports.assertBoolean = assertBoolean; +exports.assertCallerMetadata = assertCallerMetadata; +exports.assertCompact = assertCompact; +exports.assertConfigApplicableTest = assertConfigApplicableTest; +exports.assertConfigFileSearch = assertConfigFileSearch; +exports.assertFunction = assertFunction; +exports.assertIgnoreList = assertIgnoreList; +exports.assertInputSourceMap = assertInputSourceMap; +exports.assertObject = assertObject; +exports.assertPluginList = assertPluginList; +exports.assertRootMode = assertRootMode; +exports.assertSourceMaps = assertSourceMaps; +exports.assertSourceType = assertSourceType; +exports.assertString = assertString; +exports.assertTargets = assertTargets; +exports.msg = msg; + +function _helperCompilationTargets() { + const data = require("@babel/helper-compilation-targets"); + + _helperCompilationTargets = function () { + return data; + }; + + return data; +} + +var _options = require("./options"); + +function msg(loc) { + switch (loc.type) { + case "root": + return ``; + + case "env": + return `${msg(loc.parent)}.env["${loc.name}"]`; + + case "overrides": + return `${msg(loc.parent)}.overrides[${loc.index}]`; + + case "option": + return `${msg(loc.parent)}.${loc.name}`; + + case "access": + return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`; + + default: + throw new Error(`Assertion failure: Unknown type ${loc.type}`); + } +} + +function access(loc, name) { + return { + type: "access", + name, + parent: loc + }; +} + +function assertRootMode(loc, value) { + if (value !== undefined && value !== "root" && value !== "upward" && value !== "upward-optional") { + throw new Error(`${msg(loc)} must be a "root", "upward", "upward-optional" or undefined`); + } + + return value; +} + +function assertSourceMaps(loc, value) { + if (value !== undefined && typeof value !== "boolean" && value !== "inline" && value !== "both") { + throw new Error(`${msg(loc)} must be a boolean, "inline", "both", or undefined`); + } + + return value; +} + +function assertCompact(loc, value) { + if (value !== undefined && typeof value !== "boolean" && value !== "auto") { + throw new Error(`${msg(loc)} must be a boolean, "auto", or undefined`); + } + + return value; +} + +function assertSourceType(loc, value) { + if (value !== undefined && value !== "module" && value !== "script" && value !== "unambiguous") { + throw new Error(`${msg(loc)} must be "module", "script", "unambiguous", or undefined`); + } + + return value; +} + +function assertCallerMetadata(loc, value) { + const obj = assertObject(loc, value); + + if (obj) { + if (typeof obj.name !== "string") { + throw new Error(`${msg(loc)} set but does not contain "name" property string`); + } + + for (const prop of Object.keys(obj)) { + const propLoc = access(loc, prop); + const value = obj[prop]; + + if (value != null && typeof value !== "boolean" && typeof value !== "string" && typeof value !== "number") { + throw new Error(`${msg(propLoc)} must be null, undefined, a boolean, a string, or a number.`); + } + } + } + + return value; +} + +function assertInputSourceMap(loc, value) { + if (value !== undefined && typeof value !== "boolean" && (typeof value !== "object" || !value)) { + throw new Error(`${msg(loc)} must be a boolean, object, or undefined`); + } + + return value; +} + +function assertString(loc, value) { + if (value !== undefined && typeof value !== "string") { + throw new Error(`${msg(loc)} must be a string, or undefined`); + } + + return value; +} + +function assertFunction(loc, value) { + if (value !== undefined && typeof value !== "function") { + throw new Error(`${msg(loc)} must be a function, or undefined`); + } + + return value; +} + +function assertBoolean(loc, value) { + if (value !== undefined && typeof value !== "boolean") { + throw new Error(`${msg(loc)} must be a boolean, or undefined`); + } + + return value; +} + +function assertObject(loc, value) { + if (value !== undefined && (typeof value !== "object" || Array.isArray(value) || !value)) { + throw new Error(`${msg(loc)} must be an object, or undefined`); + } + + return value; +} + +function assertArray(loc, value) { + if (value != null && !Array.isArray(value)) { + throw new Error(`${msg(loc)} must be an array, or undefined`); + } + + return value; +} + +function assertIgnoreList(loc, value) { + const arr = assertArray(loc, value); + + if (arr) { + arr.forEach((item, i) => assertIgnoreItem(access(loc, i), item)); + } + + return arr; +} + +function assertIgnoreItem(loc, value) { + if (typeof value !== "string" && typeof value !== "function" && !(value instanceof RegExp)) { + throw new Error(`${msg(loc)} must be an array of string/Function/RegExp values, or undefined`); + } + + return value; +} + +function assertConfigApplicableTest(loc, value) { + if (value === undefined) return value; + + if (Array.isArray(value)) { + value.forEach((item, i) => { + if (!checkValidTest(item)) { + throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); + } + }); + } else if (!checkValidTest(value)) { + throw new Error(`${msg(loc)} must be a string/Function/RegExp, or an array of those`); + } + + return value; +} + +function checkValidTest(value) { + return typeof value === "string" || typeof value === "function" || value instanceof RegExp; +} + +function assertConfigFileSearch(loc, value) { + if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") { + throw new Error(`${msg(loc)} must be a undefined, a boolean, a string, ` + `got ${JSON.stringify(value)}`); + } + + return value; +} + +function assertBabelrcSearch(loc, value) { + if (value === undefined || typeof value === "boolean") return value; + + if (Array.isArray(value)) { + value.forEach((item, i) => { + if (!checkValidTest(item)) { + throw new Error(`${msg(access(loc, i))} must be a string/Function/RegExp.`); + } + }); + } else if (!checkValidTest(value)) { + throw new Error(`${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` + `or an array of those, got ${JSON.stringify(value)}`); + } + + return value; +} + +function assertPluginList(loc, value) { + const arr = assertArray(loc, value); + + if (arr) { + arr.forEach((item, i) => assertPluginItem(access(loc, i), item)); + } + + return arr; +} + +function assertPluginItem(loc, value) { + if (Array.isArray(value)) { + if (value.length === 0) { + throw new Error(`${msg(loc)} must include an object`); + } + + if (value.length > 3) { + throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`); + } + + assertPluginTarget(access(loc, 0), value[0]); + + if (value.length > 1) { + const opts = value[1]; + + if (opts !== undefined && opts !== false && (typeof opts !== "object" || Array.isArray(opts) || opts === null)) { + throw new Error(`${msg(access(loc, 1))} must be an object, false, or undefined`); + } + } + + if (value.length === 3) { + const name = value[2]; + + if (name !== undefined && typeof name !== "string") { + throw new Error(`${msg(access(loc, 2))} must be a string, or undefined`); + } + } + } else { + assertPluginTarget(loc, value); + } + + return value; +} + +function assertPluginTarget(loc, value) { + if ((typeof value !== "object" || !value) && typeof value !== "string" && typeof value !== "function") { + throw new Error(`${msg(loc)} must be a string, object, function`); + } + + return value; +} + +function assertTargets(loc, value) { + if ((0, _helperCompilationTargets().isBrowsersQueryValid)(value)) return value; + + if (typeof value !== "object" || !value || Array.isArray(value)) { + throw new Error(`${msg(loc)} must be a string, an array of strings or an object`); + } + + const browsersLoc = access(loc, "browsers"); + const esmodulesLoc = access(loc, "esmodules"); + assertBrowsersList(browsersLoc, value.browsers); + assertBoolean(esmodulesLoc, value.esmodules); + + for (const key of Object.keys(value)) { + const val = value[key]; + const subLoc = access(loc, key); + if (key === "esmodules") assertBoolean(subLoc, val);else if (key === "browsers") assertBrowsersList(subLoc, val);else if (!Object.hasOwnProperty.call(_helperCompilationTargets().TargetNames, key)) { + const validTargets = Object.keys(_helperCompilationTargets().TargetNames).join(", "); + throw new Error(`${msg(subLoc)} is not a valid target. Supported targets are ${validTargets}`); + } else assertBrowserVersion(subLoc, val); + } + + return value; +} + +function assertBrowsersList(loc, value) { + if (value !== undefined && !(0, _helperCompilationTargets().isBrowsersQueryValid)(value)) { + throw new Error(`${msg(loc)} must be undefined, a string or an array of strings`); + } +} + +function assertBrowserVersion(loc, value) { + if (typeof value === "number" && Math.round(value) === value) return; + if (typeof value === "string") return; + throw new Error(`${msg(loc)} must be a string or an integer number`); +} + +function assertAssumptions(loc, value) { + if (value === undefined) return; + + if (typeof value !== "object" || value === null) { + throw new Error(`${msg(loc)} must be an object or undefined.`); + } + + let root = loc; + + do { + root = root.parent; + } while (root.type !== "root"); + + const inPreset = root.source === "preset"; + + for (const name of Object.keys(value)) { + const subLoc = access(loc, name); + + if (!_options.assumptionsNames.has(name)) { + throw new Error(`${msg(subLoc)} is not a supported assumption.`); + } + + if (typeof value[name] !== "boolean") { + throw new Error(`${msg(subLoc)} must be a boolean.`); + } + + if (inPreset && value[name] === false) { + throw new Error(`${msg(subLoc)} cannot be set to 'false' inside presets.`); + } + } + + return value; +} + +0 && 0; + +//# sourceMappingURL=option-assertions.js.map diff --git a/node_modules/@babel/core/lib/config/validation/option-assertions.js.map b/node_modules/@babel/core/lib/config/validation/option-assertions.js.map new file mode 100644 index 0000000..8debd60 --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/option-assertions.js.map @@ -0,0 +1 @@ +{"version":3,"names":["msg","loc","type","parent","name","index","JSON","stringify","Error","access","assertRootMode","value","undefined","assertSourceMaps","assertCompact","assertSourceType","assertCallerMetadata","obj","assertObject","prop","Object","keys","propLoc","assertInputSourceMap","assertString","assertFunction","assertBoolean","Array","isArray","assertArray","assertIgnoreList","arr","forEach","item","i","assertIgnoreItem","RegExp","assertConfigApplicableTest","checkValidTest","assertConfigFileSearch","assertBabelrcSearch","assertPluginList","assertPluginItem","length","assertPluginTarget","opts","assertTargets","isBrowsersQueryValid","browsersLoc","esmodulesLoc","assertBrowsersList","browsers","esmodules","key","val","subLoc","hasOwnProperty","call","TargetNames","validTargets","join","assertBrowserVersion","Math","round","assertAssumptions","root","inPreset","source","assumptionsNames","has"],"sources":["../../../src/config/validation/option-assertions.ts"],"sourcesContent":["import {\n isBrowsersQueryValid,\n TargetNames,\n} from \"@babel/helper-compilation-targets\";\n\nimport type {\n ConfigFileSearch,\n BabelrcSearch,\n IgnoreList,\n IgnoreItem,\n PluginList,\n PluginItem,\n PluginTarget,\n ConfigApplicableTest,\n SourceMapsOption,\n SourceTypeOption,\n CompactOption,\n RootInputSourceMapOption,\n NestingPath,\n CallerMetadata,\n RootMode,\n TargetsListOrObject,\n AssumptionName,\n} from \"./options\";\n\nimport { assumptionsNames } from \"./options\";\n\nexport type { RootPath } from \"./options\";\n\nexport type ValidatorSet = {\n [name: string]: Validator;\n};\n\nexport type Validator = (loc: OptionPath, value: unknown) => T;\n\nexport function msg(loc: NestingPath | GeneralPath): string {\n switch (loc.type) {\n case \"root\":\n return ``;\n case \"env\":\n return `${msg(loc.parent)}.env[\"${loc.name}\"]`;\n case \"overrides\":\n return `${msg(loc.parent)}.overrides[${loc.index}]`;\n case \"option\":\n return `${msg(loc.parent)}.${loc.name}`;\n case \"access\":\n return `${msg(loc.parent)}[${JSON.stringify(loc.name)}]`;\n default:\n // @ts-expect-error should not happen when code is type checked\n throw new Error(`Assertion failure: Unknown type ${loc.type}`);\n }\n}\n\nexport function access(loc: GeneralPath, name: string | number): AccessPath {\n return {\n type: \"access\",\n name,\n parent: loc,\n };\n}\n\nexport type OptionPath = Readonly<{\n type: \"option\";\n name: string;\n parent: NestingPath;\n}>;\ntype AccessPath = Readonly<{\n type: \"access\";\n name: string | number;\n parent: GeneralPath;\n}>;\ntype GeneralPath = OptionPath | AccessPath;\n\nexport function assertRootMode(\n loc: OptionPath,\n value: unknown,\n): RootMode | void {\n if (\n value !== undefined &&\n value !== \"root\" &&\n value !== \"upward\" &&\n value !== \"upward-optional\"\n ) {\n throw new Error(\n `${msg(loc)} must be a \"root\", \"upward\", \"upward-optional\" or undefined`,\n );\n }\n return value;\n}\n\nexport function assertSourceMaps(\n loc: OptionPath,\n value: unknown,\n): SourceMapsOption | void {\n if (\n value !== undefined &&\n typeof value !== \"boolean\" &&\n value !== \"inline\" &&\n value !== \"both\"\n ) {\n throw new Error(\n `${msg(loc)} must be a boolean, \"inline\", \"both\", or undefined`,\n );\n }\n return value;\n}\n\nexport function assertCompact(\n loc: OptionPath,\n value: unknown,\n): CompactOption | void {\n if (value !== undefined && typeof value !== \"boolean\" && value !== \"auto\") {\n throw new Error(`${msg(loc)} must be a boolean, \"auto\", or undefined`);\n }\n return value;\n}\n\nexport function assertSourceType(\n loc: OptionPath,\n value: unknown,\n): SourceTypeOption | void {\n if (\n value !== undefined &&\n value !== \"module\" &&\n value !== \"script\" &&\n value !== \"unambiguous\"\n ) {\n throw new Error(\n `${msg(loc)} must be \"module\", \"script\", \"unambiguous\", or undefined`,\n );\n }\n return value;\n}\n\nexport function assertCallerMetadata(\n loc: OptionPath,\n value: unknown,\n): CallerMetadata | undefined {\n const obj = assertObject(loc, value);\n if (obj) {\n if (typeof obj.name !== \"string\") {\n throw new Error(\n `${msg(loc)} set but does not contain \"name\" property string`,\n );\n }\n\n for (const prop of Object.keys(obj)) {\n const propLoc = access(loc, prop);\n const value = obj[prop];\n if (\n value != null &&\n typeof value !== \"boolean\" &&\n typeof value !== \"string\" &&\n typeof value !== \"number\"\n ) {\n // NOTE(logan): I'm limiting the type here so that we can guarantee that\n // the \"caller\" value will serialize to JSON nicely. We can always\n // allow more complex structures later though.\n throw new Error(\n `${msg(\n propLoc,\n )} must be null, undefined, a boolean, a string, or a number.`,\n );\n }\n }\n }\n // @ts-expect-error todo(flow->ts)\n return value;\n}\n\nexport function assertInputSourceMap(\n loc: OptionPath,\n value: unknown,\n): RootInputSourceMapOption | void {\n if (\n value !== undefined &&\n typeof value !== \"boolean\" &&\n (typeof value !== \"object\" || !value)\n ) {\n throw new Error(`${msg(loc)} must be a boolean, object, or undefined`);\n }\n return value;\n}\n\nexport function assertString(loc: GeneralPath, value: unknown): string | void {\n if (value !== undefined && typeof value !== \"string\") {\n throw new Error(`${msg(loc)} must be a string, or undefined`);\n }\n return value;\n}\n\nexport function assertFunction(\n loc: GeneralPath,\n value: unknown,\n): Function | void {\n if (value !== undefined && typeof value !== \"function\") {\n throw new Error(`${msg(loc)} must be a function, or undefined`);\n }\n return value;\n}\n\nexport function assertBoolean(\n loc: GeneralPath,\n value: unknown,\n): boolean | void {\n if (value !== undefined && typeof value !== \"boolean\") {\n throw new Error(`${msg(loc)} must be a boolean, or undefined`);\n }\n return value;\n}\n\nexport function assertObject(\n loc: GeneralPath,\n value: unknown,\n): { readonly [key: string]: unknown } | void {\n if (\n value !== undefined &&\n (typeof value !== \"object\" || Array.isArray(value) || !value)\n ) {\n throw new Error(`${msg(loc)} must be an object, or undefined`);\n }\n // @ts-expect-error todo(flow->ts) value is still typed as unknown, also assert function typically should not return a value\n return value;\n}\n\nexport function assertArray(\n loc: GeneralPath,\n value: Array | undefined | null,\n): ReadonlyArray | undefined | null {\n if (value != null && !Array.isArray(value)) {\n throw new Error(`${msg(loc)} must be an array, or undefined`);\n }\n return value;\n}\n\nexport function assertIgnoreList(\n loc: OptionPath,\n value: unknown[] | undefined,\n): IgnoreList | void {\n const arr = assertArray(loc, value);\n if (arr) {\n arr.forEach((item, i) => assertIgnoreItem(access(loc, i), item));\n }\n // @ts-expect-error todo(flow->ts)\n return arr;\n}\nfunction assertIgnoreItem(loc: GeneralPath, value: unknown): IgnoreItem {\n if (\n typeof value !== \"string\" &&\n typeof value !== \"function\" &&\n !(value instanceof RegExp)\n ) {\n throw new Error(\n `${msg(\n loc,\n )} must be an array of string/Function/RegExp values, or undefined`,\n );\n }\n return value as IgnoreItem;\n}\n\nexport function assertConfigApplicableTest(\n loc: OptionPath,\n value: unknown,\n): ConfigApplicableTest | void {\n if (value === undefined) return value;\n\n if (Array.isArray(value)) {\n value.forEach((item, i) => {\n if (!checkValidTest(item)) {\n throw new Error(\n `${msg(access(loc, i))} must be a string/Function/RegExp.`,\n );\n }\n });\n } else if (!checkValidTest(value)) {\n throw new Error(\n `${msg(loc)} must be a string/Function/RegExp, or an array of those`,\n );\n }\n return value as ConfigApplicableTest;\n}\n\nfunction checkValidTest(value: unknown): value is string | Function | RegExp {\n return (\n typeof value === \"string\" ||\n typeof value === \"function\" ||\n value instanceof RegExp\n );\n}\n\nexport function assertConfigFileSearch(\n loc: OptionPath,\n value: unknown,\n): ConfigFileSearch | void {\n if (\n value !== undefined &&\n typeof value !== \"boolean\" &&\n typeof value !== \"string\"\n ) {\n throw new Error(\n `${msg(loc)} must be a undefined, a boolean, a string, ` +\n `got ${JSON.stringify(value)}`,\n );\n }\n\n return value;\n}\n\nexport function assertBabelrcSearch(\n loc: OptionPath,\n value: unknown,\n): BabelrcSearch | void {\n if (value === undefined || typeof value === \"boolean\") return value;\n\n if (Array.isArray(value)) {\n value.forEach((item, i) => {\n if (!checkValidTest(item)) {\n throw new Error(\n `${msg(access(loc, i))} must be a string/Function/RegExp.`,\n );\n }\n });\n } else if (!checkValidTest(value)) {\n throw new Error(\n `${msg(loc)} must be a undefined, a boolean, a string/Function/RegExp ` +\n `or an array of those, got ${JSON.stringify(value as any)}`,\n );\n }\n return value as BabelrcSearch;\n}\n\nexport function assertPluginList(\n loc: OptionPath,\n value: unknown[] | null | undefined,\n): PluginList | void {\n const arr = assertArray(loc, value);\n if (arr) {\n // Loop instead of using `.map` in order to preserve object identity\n // for plugin array for use during config chain processing.\n arr.forEach((item, i) => assertPluginItem(access(loc, i), item));\n }\n return arr as any;\n}\nfunction assertPluginItem(loc: GeneralPath, value: unknown): PluginItem {\n if (Array.isArray(value)) {\n if (value.length === 0) {\n throw new Error(`${msg(loc)} must include an object`);\n }\n\n if (value.length > 3) {\n throw new Error(`${msg(loc)} may only be a two-tuple or three-tuple`);\n }\n\n assertPluginTarget(access(loc, 0), value[0]);\n\n if (value.length > 1) {\n const opts = value[1];\n if (\n opts !== undefined &&\n opts !== false &&\n (typeof opts !== \"object\" || Array.isArray(opts) || opts === null)\n ) {\n throw new Error(\n `${msg(access(loc, 1))} must be an object, false, or undefined`,\n );\n }\n }\n if (value.length === 3) {\n const name = value[2];\n if (name !== undefined && typeof name !== \"string\") {\n throw new Error(\n `${msg(access(loc, 2))} must be a string, or undefined`,\n );\n }\n }\n } else {\n assertPluginTarget(loc, value);\n }\n\n // @ts-expect-error todo(flow->ts)\n return value;\n}\nfunction assertPluginTarget(loc: GeneralPath, value: unknown): PluginTarget {\n if (\n (typeof value !== \"object\" || !value) &&\n typeof value !== \"string\" &&\n typeof value !== \"function\"\n ) {\n throw new Error(`${msg(loc)} must be a string, object, function`);\n }\n return value;\n}\n\nexport function assertTargets(\n loc: GeneralPath,\n value: any,\n): TargetsListOrObject {\n if (isBrowsersQueryValid(value)) return value;\n\n if (typeof value !== \"object\" || !value || Array.isArray(value)) {\n throw new Error(\n `${msg(loc)} must be a string, an array of strings or an object`,\n );\n }\n\n const browsersLoc = access(loc, \"browsers\");\n const esmodulesLoc = access(loc, \"esmodules\");\n\n assertBrowsersList(browsersLoc, value.browsers);\n assertBoolean(esmodulesLoc, value.esmodules);\n\n for (const key of Object.keys(value)) {\n const val = value[key];\n const subLoc = access(loc, key);\n\n if (key === \"esmodules\") assertBoolean(subLoc, val);\n else if (key === \"browsers\") assertBrowsersList(subLoc, val);\n else if (!Object.hasOwnProperty.call(TargetNames, key)) {\n const validTargets = Object.keys(TargetNames).join(\", \");\n throw new Error(\n `${msg(\n subLoc,\n )} is not a valid target. Supported targets are ${validTargets}`,\n );\n } else assertBrowserVersion(subLoc, val);\n }\n\n return value;\n}\n\nfunction assertBrowsersList(loc: GeneralPath, value: unknown) {\n if (value !== undefined && !isBrowsersQueryValid(value)) {\n throw new Error(\n `${msg(loc)} must be undefined, a string or an array of strings`,\n );\n }\n}\n\nfunction assertBrowserVersion(loc: GeneralPath, value: unknown) {\n if (typeof value === \"number\" && Math.round(value) === value) return;\n if (typeof value === \"string\") return;\n\n throw new Error(`${msg(loc)} must be a string or an integer number`);\n}\n\nexport function assertAssumptions(\n loc: GeneralPath,\n value: { [key: string]: unknown },\n): { [name: string]: boolean } | void {\n if (value === undefined) return;\n\n if (typeof value !== \"object\" || value === null) {\n throw new Error(`${msg(loc)} must be an object or undefined.`);\n }\n\n // todo(flow->ts): remove any\n let root: any = loc;\n do {\n root = root.parent;\n } while (root.type !== \"root\");\n const inPreset = root.source === \"preset\";\n\n for (const name of Object.keys(value)) {\n const subLoc = access(loc, name);\n if (!assumptionsNames.has(name as AssumptionName)) {\n throw new Error(`${msg(subLoc)} is not a supported assumption.`);\n }\n if (typeof value[name] !== \"boolean\") {\n throw new Error(`${msg(subLoc)} must be a boolean.`);\n }\n if (inPreset && value[name] === false) {\n throw new Error(\n `${msg(subLoc)} cannot be set to 'false' inside presets.`,\n );\n }\n }\n\n // @ts-expect-error todo(flow->ts)\n return value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAyBA;;AAUO,SAASA,GAAT,CAAaC,GAAb,EAAqD;EAC1D,QAAQA,GAAG,CAACC,IAAZ;IACE,KAAK,MAAL;MACE,OAAQ,EAAR;;IACF,KAAK,KAAL;MACE,OAAQ,GAAEF,GAAG,CAACC,GAAG,CAACE,MAAL,CAAa,SAAQF,GAAG,CAACG,IAAK,IAA3C;;IACF,KAAK,WAAL;MACE,OAAQ,GAAEJ,GAAG,CAACC,GAAG,CAACE,MAAL,CAAa,cAAaF,GAAG,CAACI,KAAM,GAAjD;;IACF,KAAK,QAAL;MACE,OAAQ,GAAEL,GAAG,CAACC,GAAG,CAACE,MAAL,CAAa,IAAGF,GAAG,CAACG,IAAK,EAAtC;;IACF,KAAK,QAAL;MACE,OAAQ,GAAEJ,GAAG,CAACC,GAAG,CAACE,MAAL,CAAa,IAAGG,IAAI,CAACC,SAAL,CAAeN,GAAG,CAACG,IAAnB,CAAyB,GAAtD;;IACF;MAEE,MAAM,IAAII,KAAJ,CAAW,mCAAkCP,GAAG,CAACC,IAAK,EAAtD,CAAN;EAbJ;AAeD;;AAEM,SAASO,MAAT,CAAgBR,GAAhB,EAAkCG,IAAlC,EAAqE;EAC1E,OAAO;IACLF,IAAI,EAAE,QADD;IAELE,IAFK;IAGLD,MAAM,EAAEF;EAHH,CAAP;AAKD;;AAcM,SAASS,cAAT,CACLT,GADK,EAELU,KAFK,EAGY;EACjB,IACEA,KAAK,KAAKC,SAAV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AYV,KAAZ,CAAnB,EAAuC;IACrC,MAAM4C,MAAM,GAAG9C,MAAM,CAACR,GAAD,EAAMG,IAAN,CAArB;;IACA,IAAI,CAACgE,yBAAA,CAAiBC,GAAjB,CAAqBjE,IAArB,CAAL,EAAmD;MACjD,MAAM,IAAII,KAAJ,CAAW,GAAER,GAAG,CAACuD,MAAD,CAAS,iCAAzB,CAAN;IACD;;IACD,IAAI,OAAO5C,KAAK,CAACP,IAAD,CAAZ,KAAuB,SAA3B,EAAsC;MACpC,MAAM,IAAII,KAAJ,CAAW,GAAER,GAAG,CAACuD,MAAD,CAAS,qBAAzB,CAAN;IACD;;IACD,IAAIW,QAAQ,IAAIvD,KAAK,CAACP,IAAD,CAAL,KAAgB,KAAhC,EAAuC;MACrC,MAAM,IAAII,KAAJ,CACH,GAAER,GAAG,CAACuD,MAAD,CAAS,2CADX,CAAN;IAGD;EACF;;EAGD,OAAO5C,KAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/validation/options.js b/node_modules/@babel/core/lib/config/validation/options.js new file mode 100644 index 0000000..3bb31cf --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/options.js @@ -0,0 +1,221 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assumptionsNames = void 0; +exports.checkNoUnwrappedItemOptionPairs = checkNoUnwrappedItemOptionPairs; +exports.validate = validate; + +var _removed = require("./removed"); + +var _optionAssertions = require("./option-assertions"); + +var _configError = require("../../errors/config-error"); + +const ROOT_VALIDATORS = { + cwd: _optionAssertions.assertString, + root: _optionAssertions.assertString, + rootMode: _optionAssertions.assertRootMode, + configFile: _optionAssertions.assertConfigFileSearch, + caller: _optionAssertions.assertCallerMetadata, + filename: _optionAssertions.assertString, + filenameRelative: _optionAssertions.assertString, + code: _optionAssertions.assertBoolean, + ast: _optionAssertions.assertBoolean, + cloneInputAst: _optionAssertions.assertBoolean, + envName: _optionAssertions.assertString +}; +const BABELRC_VALIDATORS = { + babelrc: _optionAssertions.assertBoolean, + babelrcRoots: _optionAssertions.assertBabelrcSearch +}; +const NONPRESET_VALIDATORS = { + extends: _optionAssertions.assertString, + ignore: _optionAssertions.assertIgnoreList, + only: _optionAssertions.assertIgnoreList, + targets: _optionAssertions.assertTargets, + browserslistConfigFile: _optionAssertions.assertConfigFileSearch, + browserslistEnv: _optionAssertions.assertString +}; +const COMMON_VALIDATORS = { + inputSourceMap: _optionAssertions.assertInputSourceMap, + presets: _optionAssertions.assertPluginList, + plugins: _optionAssertions.assertPluginList, + passPerPreset: _optionAssertions.assertBoolean, + assumptions: _optionAssertions.assertAssumptions, + env: assertEnvSet, + overrides: assertOverridesList, + test: _optionAssertions.assertConfigApplicableTest, + include: _optionAssertions.assertConfigApplicableTest, + exclude: _optionAssertions.assertConfigApplicableTest, + retainLines: _optionAssertions.assertBoolean, + comments: _optionAssertions.assertBoolean, + shouldPrintComment: _optionAssertions.assertFunction, + compact: _optionAssertions.assertCompact, + minified: _optionAssertions.assertBoolean, + auxiliaryCommentBefore: _optionAssertions.assertString, + auxiliaryCommentAfter: _optionAssertions.assertString, + sourceType: _optionAssertions.assertSourceType, + wrapPluginVisitorMethod: _optionAssertions.assertFunction, + highlightCode: _optionAssertions.assertBoolean, + sourceMaps: _optionAssertions.assertSourceMaps, + sourceMap: _optionAssertions.assertSourceMaps, + sourceFileName: _optionAssertions.assertString, + sourceRoot: _optionAssertions.assertString, + parserOpts: _optionAssertions.assertObject, + generatorOpts: _optionAssertions.assertObject +}; +{ + Object.assign(COMMON_VALIDATORS, { + getModuleId: _optionAssertions.assertFunction, + moduleRoot: _optionAssertions.assertString, + moduleIds: _optionAssertions.assertBoolean, + moduleId: _optionAssertions.assertString + }); +} +const knownAssumptions = ["arrayLikeIsIterable", "constantReexports", "constantSuper", "enumerableModuleMeta", "ignoreFunctionLength", "ignoreToPrimitiveHint", "iterableIsArray", "mutableTemplateObject", "noClassCalls", "noDocumentAll", "noIncompleteNsImportDetection", "noNewArrows", "objectRestNoSymbols", "privateFieldsAsProperties", "pureGetters", "setClassMethods", "setComputedProperties", "setPublicClassFields", "setSpreadProperties", "skipForOfIteratorClosing", "superIsCallableConstructor"]; +const assumptionsNames = new Set(knownAssumptions); +exports.assumptionsNames = assumptionsNames; + +function getSource(loc) { + return loc.type === "root" ? loc.source : getSource(loc.parent); +} + +function validate(type, opts, filename) { + try { + return validateNested({ + type: "root", + source: type + }, opts); + } catch (error) { + const configError = new _configError.default(error.message, filename); + if (error.code) configError.code = error.code; + throw configError; + } +} + +function validateNested(loc, opts) { + const type = getSource(loc); + assertNoDuplicateSourcemap(opts); + Object.keys(opts).forEach(key => { + const optLoc = { + type: "option", + name: key, + parent: loc + }; + + if (type === "preset" && NONPRESET_VALIDATORS[key]) { + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in preset options`); + } + + if (type !== "arguments" && ROOT_VALIDATORS[key]) { + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options`); + } + + if (type !== "arguments" && type !== "configfile" && BABELRC_VALIDATORS[key]) { + if (type === "babelrcfile" || type === "extendsfile") { + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is not allowed in .babelrc or "extends"ed files, only in root programmatic options, ` + `or babel.config.js/config file options`); + } + + throw new Error(`${(0, _optionAssertions.msg)(optLoc)} is only allowed in root programmatic options, or babel.config.js/config file options`); + } + + const validator = COMMON_VALIDATORS[key] || NONPRESET_VALIDATORS[key] || BABELRC_VALIDATORS[key] || ROOT_VALIDATORS[key] || throwUnknownError; + validator(optLoc, opts[key]); + }); + return opts; +} + +function throwUnknownError(loc) { + const key = loc.name; + + if (_removed.default[key]) { + const { + message, + version = 5 + } = _removed.default[key]; + throw new Error(`Using removed Babel ${version} option: ${(0, _optionAssertions.msg)(loc)} - ${message}`); + } else { + const unknownOptErr = new Error(`Unknown option: ${(0, _optionAssertions.msg)(loc)}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`); + unknownOptErr.code = "BABEL_UNKNOWN_OPTION"; + throw unknownOptErr; + } +} + +function has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +function assertNoDuplicateSourcemap(opts) { + if (has(opts, "sourceMap") && has(opts, "sourceMaps")) { + throw new Error(".sourceMap is an alias for .sourceMaps, cannot use both"); + } +} + +function assertEnvSet(loc, value) { + if (loc.parent.type === "env") { + throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside of another .env block`); + } + + const parent = loc.parent; + const obj = (0, _optionAssertions.assertObject)(loc, value); + + if (obj) { + for (const envName of Object.keys(obj)) { + const env = (0, _optionAssertions.assertObject)((0, _optionAssertions.access)(loc, envName), obj[envName]); + if (!env) continue; + const envLoc = { + type: "env", + name: envName, + parent + }; + validateNested(envLoc, env); + } + } + + return obj; +} + +function assertOverridesList(loc, value) { + if (loc.parent.type === "env") { + throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .env block`); + } + + if (loc.parent.type === "overrides") { + throw new Error(`${(0, _optionAssertions.msg)(loc)} is not allowed inside an .overrides block`); + } + + const parent = loc.parent; + const arr = (0, _optionAssertions.assertArray)(loc, value); + + if (arr) { + for (const [index, item] of arr.entries()) { + const objLoc = (0, _optionAssertions.access)(loc, index); + const env = (0, _optionAssertions.assertObject)(objLoc, item); + if (!env) throw new Error(`${(0, _optionAssertions.msg)(objLoc)} must be an object`); + const overridesLoc = { + type: "overrides", + index, + parent + }; + validateNested(overridesLoc, env); + } + } + + return arr; +} + +function checkNoUnwrappedItemOptionPairs(items, index, type, e) { + if (index === 0) return; + const lastItem = items[index - 1]; + const thisItem = items[index]; + + if (lastItem.file && lastItem.options === undefined && typeof thisItem.value === "object") { + e.message += `\n- Maybe you meant to use\n` + `"${type}s": [\n ["${lastItem.file.request}", ${JSON.stringify(thisItem.value, undefined, 2)}]\n]\n` + `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`; + } +} + +0 && 0; + +//# sourceMappingURL=options.js.map diff --git a/node_modules/@babel/core/lib/config/validation/options.js.map b/node_modules/@babel/core/lib/config/validation/options.js.map new file mode 100644 index 0000000..684fcde --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/options.js.map @@ -0,0 +1 @@ +{"version":3,"names":["ROOT_VALIDATORS","cwd","assertString","root","rootMode","assertRootMode","configFile","assertConfigFileSearch","caller","assertCallerMetadata","filename","filenameRelative","code","assertBoolean","ast","cloneInputAst","envName","BABELRC_VALIDATORS","babelrc","babelrcRoots","assertBabelrcSearch","NONPRESET_VALIDATORS","extends","ignore","assertIgnoreList","only","targets","assertTargets","browserslistConfigFile","browserslistEnv","COMMON_VALIDATORS","inputSourceMap","assertInputSourceMap","presets","assertPluginList","plugins","passPerPreset","assumptions","assertAssumptions","env","assertEnvSet","overrides","assertOverridesList","test","assertConfigApplicableTest","include","exclude","retainLines","comments","shouldPrintComment","assertFunction","compact","assertCompact","minified","auxiliaryCommentBefore","auxiliaryCommentAfter","sourceType","assertSourceType","wrapPluginVisitorMethod","highlightCode","sourceMaps","assertSourceMaps","sourceMap","sourceFileName","sourceRoot","parserOpts","assertObject","generatorOpts","Object","assign","getModuleId","moduleRoot","moduleIds","moduleId","knownAssumptions","assumptionsNames","Set","getSource","loc","type","source","parent","validate","opts","validateNested","error","configError","ConfigError","message","assertNoDuplicateSourcemap","keys","forEach","key","optLoc","name","Error","msg","validator","throwUnknownError","removed","version","unknownOptErr","has","obj","prototype","hasOwnProperty","call","value","access","envLoc","arr","assertArray","index","item","entries","objLoc","overridesLoc","checkNoUnwrappedItemOptionPairs","items","e","lastItem","thisItem","file","options","undefined","request","JSON","stringify"],"sources":["../../../src/config/validation/options.ts"],"sourcesContent":["import type { InputTargets, Targets } from \"@babel/helper-compilation-targets\";\n\nimport type { ConfigItem } from \"../item\";\nimport type Plugin from \"../plugin\";\n\nimport removed from \"./removed\";\nimport {\n msg,\n access,\n assertString,\n assertBoolean,\n assertObject,\n assertArray,\n assertCallerMetadata,\n assertInputSourceMap,\n assertIgnoreList,\n assertPluginList,\n assertConfigApplicableTest,\n assertConfigFileSearch,\n assertBabelrcSearch,\n assertFunction,\n assertRootMode,\n assertSourceMaps,\n assertCompact,\n assertSourceType,\n assertTargets,\n assertAssumptions,\n} from \"./option-assertions\";\nimport type { ValidatorSet, Validator, OptionPath } from \"./option-assertions\";\nimport type { UnloadedDescriptor } from \"../config-descriptors\";\nimport type { ParserOptions } from \"@babel/parser\";\nimport type { GeneratorOptions } from \"@babel/generator\";\nimport ConfigError from \"../../errors/config-error\";\n\nconst ROOT_VALIDATORS: ValidatorSet = {\n cwd: assertString as Validator,\n root: assertString as Validator,\n rootMode: assertRootMode as Validator,\n configFile: assertConfigFileSearch as Validator<\n ValidatedOptions[\"configFile\"]\n >,\n\n caller: assertCallerMetadata as Validator,\n filename: assertString as Validator,\n filenameRelative: assertString as Validator<\n ValidatedOptions[\"filenameRelative\"]\n >,\n code: assertBoolean as Validator,\n ast: assertBoolean as Validator,\n\n cloneInputAst: assertBoolean as Validator,\n\n envName: assertString as Validator,\n};\n\nconst BABELRC_VALIDATORS: ValidatorSet = {\n babelrc: assertBoolean as Validator,\n babelrcRoots: assertBabelrcSearch as Validator<\n ValidatedOptions[\"babelrcRoots\"]\n >,\n};\n\nconst NONPRESET_VALIDATORS: ValidatorSet = {\n extends: assertString as Validator,\n ignore: assertIgnoreList as Validator,\n only: assertIgnoreList as Validator,\n\n targets: assertTargets as Validator,\n browserslistConfigFile: assertConfigFileSearch as Validator<\n ValidatedOptions[\"browserslistConfigFile\"]\n >,\n browserslistEnv: assertString as Validator<\n ValidatedOptions[\"browserslistEnv\"]\n >,\n};\n\nconst COMMON_VALIDATORS: ValidatorSet = {\n // TODO: Should 'inputSourceMap' be moved to be a root-only option?\n // We may want a boolean-only version to be a common option, with the\n // object only allowed as a root config argument.\n inputSourceMap: assertInputSourceMap as Validator<\n ValidatedOptions[\"inputSourceMap\"]\n >,\n presets: assertPluginList as Validator,\n plugins: assertPluginList as Validator,\n passPerPreset: assertBoolean as Validator,\n assumptions: assertAssumptions as Validator,\n\n env: assertEnvSet as Validator,\n overrides: assertOverridesList as Validator,\n\n // We could limit these to 'overrides' blocks, but it's not clear why we'd\n // bother, when the ability to limit a config to a specific set of files\n // is a fairly general useful feature.\n test: assertConfigApplicableTest as Validator,\n include: assertConfigApplicableTest as Validator,\n exclude: assertConfigApplicableTest as Validator,\n\n retainLines: assertBoolean as Validator,\n comments: assertBoolean as Validator,\n shouldPrintComment: assertFunction as Validator<\n ValidatedOptions[\"shouldPrintComment\"]\n >,\n compact: assertCompact as Validator,\n minified: assertBoolean as Validator,\n auxiliaryCommentBefore: assertString as Validator<\n ValidatedOptions[\"auxiliaryCommentBefore\"]\n >,\n auxiliaryCommentAfter: assertString as Validator<\n ValidatedOptions[\"auxiliaryCommentAfter\"]\n >,\n sourceType: assertSourceType as Validator,\n wrapPluginVisitorMethod: assertFunction as Validator<\n ValidatedOptions[\"wrapPluginVisitorMethod\"]\n >,\n highlightCode: assertBoolean as Validator,\n sourceMaps: assertSourceMaps as Validator,\n sourceMap: assertSourceMaps as Validator,\n sourceFileName: assertString as Validator,\n sourceRoot: assertString as Validator,\n parserOpts: assertObject as Validator,\n generatorOpts: assertObject as Validator,\n};\nif (!process.env.BABEL_8_BREAKING) {\n Object.assign(COMMON_VALIDATORS, {\n getModuleId: assertFunction,\n moduleRoot: assertString,\n moduleIds: assertBoolean,\n moduleId: assertString,\n });\n}\n\nexport type InputOptions = ValidatedOptions;\n\nexport type ValidatedOptions = {\n cwd?: string;\n filename?: string;\n filenameRelative?: string;\n babelrc?: boolean;\n babelrcRoots?: BabelrcSearch;\n configFile?: ConfigFileSearch;\n root?: string;\n rootMode?: RootMode;\n code?: boolean;\n ast?: boolean;\n cloneInputAst?: boolean;\n inputSourceMap?: RootInputSourceMapOption;\n envName?: string;\n caller?: CallerMetadata;\n extends?: string;\n env?: EnvSet;\n ignore?: IgnoreList;\n only?: IgnoreList;\n overrides?: OverridesList;\n // Generally verify if a given config object should be applied to the given file.\n test?: ConfigApplicableTest;\n include?: ConfigApplicableTest;\n exclude?: ConfigApplicableTest;\n presets?: PluginList;\n plugins?: PluginList;\n passPerPreset?: boolean;\n assumptions?: {\n [name: string]: boolean;\n };\n // browserslists-related options\n targets?: TargetsListOrObject;\n browserslistConfigFile?: ConfigFileSearch;\n browserslistEnv?: string;\n // Options for @babel/generator\n retainLines?: boolean;\n comments?: boolean;\n shouldPrintComment?: Function;\n compact?: CompactOption;\n minified?: boolean;\n auxiliaryCommentBefore?: string;\n auxiliaryCommentAfter?: string;\n // Parser\n sourceType?: SourceTypeOption;\n wrapPluginVisitorMethod?: Function;\n highlightCode?: boolean;\n // Sourcemap generation options.\n sourceMaps?: SourceMapsOption;\n sourceMap?: SourceMapsOption;\n sourceFileName?: string;\n sourceRoot?: string;\n // Deprecate top level parserOpts\n parserOpts?: ParserOptions;\n // Deprecate top level generatorOpts\n generatorOpts?: GeneratorOptions;\n};\n\nexport type NormalizedOptions = {\n readonly targets: Targets;\n} & Omit;\n\nexport type CallerMetadata = {\n // If 'caller' is specified, require that the name is given for debugging\n // messages.\n name: string;\n};\nexport type EnvSet = {\n [x: string]: T;\n};\nexport type IgnoreItem =\n | string\n | RegExp\n | ((\n path: string | undefined,\n context: { dirname: string; caller: CallerMetadata; envName: string },\n ) => unknown);\nexport type IgnoreList = ReadonlyArray;\n\nexport type PluginOptions = object | void | false;\nexport type PluginTarget = string | object | Function;\nexport type PluginItem =\n | ConfigItem\n | Plugin\n | PluginTarget\n | [PluginTarget, PluginOptions]\n | [PluginTarget, PluginOptions, string | void];\nexport type PluginList = ReadonlyArray;\n\nexport type OverridesList = Array;\nexport type ConfigApplicableTest = IgnoreItem | Array;\n\nexport type ConfigFileSearch = string | boolean;\nexport type BabelrcSearch = boolean | IgnoreItem | IgnoreList;\nexport type SourceMapsOption = boolean | \"inline\" | \"both\";\nexport type SourceTypeOption = \"module\" | \"script\" | \"unambiguous\";\nexport type CompactOption = boolean | \"auto\";\nexport type RootInputSourceMapOption = {} | boolean;\nexport type RootMode = \"root\" | \"upward\" | \"upward-optional\";\n\nexport type TargetsListOrObject =\n | Targets\n | InputTargets\n | InputTargets[\"browsers\"];\n\nexport type OptionsSource =\n | \"arguments\"\n | \"configfile\"\n | \"babelrcfile\"\n | \"extendsfile\"\n | \"preset\"\n | \"plugin\";\n\nexport type RootPath = Readonly<{\n type: \"root\";\n source: OptionsSource;\n}>;\n\ntype OverridesPath = Readonly<{\n type: \"overrides\";\n index: number;\n parent: RootPath;\n}>;\n\ntype EnvPath = Readonly<{\n type: \"env\";\n name: string;\n parent: RootPath | OverridesPath;\n}>;\n\nexport type NestingPath = RootPath | OverridesPath | EnvPath;\n\nconst knownAssumptions = [\n \"arrayLikeIsIterable\",\n \"constantReexports\",\n \"constantSuper\",\n \"enumerableModuleMeta\",\n \"ignoreFunctionLength\",\n \"ignoreToPrimitiveHint\",\n \"iterableIsArray\",\n \"mutableTemplateObject\",\n \"noClassCalls\",\n \"noDocumentAll\",\n \"noIncompleteNsImportDetection\",\n \"noNewArrows\",\n \"objectRestNoSymbols\",\n \"privateFieldsAsProperties\",\n \"pureGetters\",\n \"setClassMethods\",\n \"setComputedProperties\",\n \"setPublicClassFields\",\n \"setSpreadProperties\",\n \"skipForOfIteratorClosing\",\n \"superIsCallableConstructor\",\n] as const;\nexport type AssumptionName = typeof knownAssumptions[number];\nexport const assumptionsNames = new Set(knownAssumptions);\n\nfunction getSource(loc: NestingPath): OptionsSource {\n return loc.type === \"root\" ? loc.source : getSource(loc.parent);\n}\n\nexport function validate(\n type: OptionsSource,\n opts: {},\n filename?: string,\n): ValidatedOptions {\n try {\n return validateNested(\n {\n type: \"root\",\n source: type,\n },\n opts,\n );\n } catch (error) {\n const configError = new ConfigError(error.message, filename);\n // @ts-expect-error TODO: .code is not defined on ConfigError or Error\n if (error.code) configError.code = error.code;\n throw configError;\n }\n}\n\nfunction validateNested(loc: NestingPath, opts: { [key: string]: unknown }) {\n const type = getSource(loc);\n\n assertNoDuplicateSourcemap(opts);\n\n Object.keys(opts).forEach((key: string) => {\n const optLoc = {\n type: \"option\",\n name: key,\n parent: loc,\n } as const;\n\n if (type === \"preset\" && NONPRESET_VALIDATORS[key]) {\n throw new Error(`${msg(optLoc)} is not allowed in preset options`);\n }\n if (type !== \"arguments\" && ROOT_VALIDATORS[key]) {\n throw new Error(\n `${msg(optLoc)} is only allowed in root programmatic options`,\n );\n }\n if (\n type !== \"arguments\" &&\n type !== \"configfile\" &&\n BABELRC_VALIDATORS[key]\n ) {\n if (type === \"babelrcfile\" || type === \"extendsfile\") {\n throw new Error(\n `${msg(\n optLoc,\n )} is not allowed in .babelrc or \"extends\"ed files, only in root programmatic options, ` +\n `or babel.config.js/config file options`,\n );\n }\n\n throw new Error(\n `${msg(\n optLoc,\n )} is only allowed in root programmatic options, or babel.config.js/config file options`,\n );\n }\n\n const validator =\n COMMON_VALIDATORS[key] ||\n NONPRESET_VALIDATORS[key] ||\n BABELRC_VALIDATORS[key] ||\n ROOT_VALIDATORS[key] ||\n (throwUnknownError as Validator);\n\n validator(optLoc, opts[key]);\n });\n\n return opts;\n}\n\nfunction throwUnknownError(loc: OptionPath) {\n const key = loc.name;\n\n if (removed[key]) {\n const { message, version = 5 } = removed[key];\n\n throw new Error(\n `Using removed Babel ${version} option: ${msg(loc)} - ${message}`,\n );\n } else {\n // eslint-disable-next-line max-len\n const unknownOptErr = new Error(\n `Unknown option: ${msg(\n loc,\n )}. Check out https://babeljs.io/docs/en/babel-core/#options for more information about options.`,\n );\n // @ts-expect-error todo(flow->ts): consider creating something like BabelConfigError with code field in it\n unknownOptErr.code = \"BABEL_UNKNOWN_OPTION\";\n\n throw unknownOptErr;\n }\n}\n\nfunction has(obj: {}, key: string) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nfunction assertNoDuplicateSourcemap(opts: {}): void {\n if (has(opts, \"sourceMap\") && has(opts, \"sourceMaps\")) {\n throw new Error(\".sourceMap is an alias for .sourceMaps, cannot use both\");\n }\n}\n\nfunction assertEnvSet(\n loc: OptionPath,\n value: unknown,\n): void | EnvSet {\n if (loc.parent.type === \"env\") {\n throw new Error(`${msg(loc)} is not allowed inside of another .env block`);\n }\n const parent: RootPath | OverridesPath = loc.parent;\n\n const obj = assertObject(loc, value);\n if (obj) {\n // Validate but don't copy the .env object in order to preserve\n // object identity for use during config chain processing.\n for (const envName of Object.keys(obj)) {\n const env = assertObject(access(loc, envName), obj[envName]);\n if (!env) continue;\n\n const envLoc = {\n type: \"env\",\n name: envName,\n parent,\n } as const;\n validateNested(envLoc, env);\n }\n }\n return obj;\n}\n\nfunction assertOverridesList(\n loc: OptionPath,\n value: unknown[],\n): undefined | OverridesList {\n if (loc.parent.type === \"env\") {\n throw new Error(`${msg(loc)} is not allowed inside an .env block`);\n }\n if (loc.parent.type === \"overrides\") {\n throw new Error(`${msg(loc)} is not allowed inside an .overrides block`);\n }\n const parent: RootPath = loc.parent;\n\n const arr = assertArray(loc, value);\n if (arr) {\n for (const [index, item] of arr.entries()) {\n const objLoc = access(loc, index);\n const env = assertObject(objLoc, item);\n if (!env) throw new Error(`${msg(objLoc)} must be an object`);\n\n const overridesLoc = {\n type: \"overrides\",\n index,\n parent,\n } as const;\n validateNested(overridesLoc, env);\n }\n }\n return arr as OverridesList;\n}\n\nexport function checkNoUnwrappedItemOptionPairs(\n items: Array,\n index: number,\n type: \"plugin\" | \"preset\",\n e: Error,\n): void {\n if (index === 0) return;\n\n const lastItem = items[index - 1];\n const thisItem = items[index];\n\n if (\n lastItem.file &&\n lastItem.options === undefined &&\n typeof thisItem.value === \"object\"\n ) {\n e.message +=\n `\\n- Maybe you meant to use\\n` +\n `\"${type}s\": [\\n [\"${lastItem.file.request}\", ${JSON.stringify(\n thisItem.value,\n undefined,\n 2,\n )}]\\n]\\n` +\n `To be a valid ${type}, its name and options should be wrapped in a pair of brackets`;\n }\n}\n"],"mappings":";;;;;;;;;AAKA;;AACA;;AA0BA;;AAEA,MAAMA,eAA6B,GAAG;EACpCC,GAAG,EAAEC,8BAD+B;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node_modules/@babel/core/lib/config/validation/plugins.js b/node_modules/@babel/core/lib/config/validation/plugins.js new file mode 100644 index 0000000..ec83896 --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/plugins.js @@ -0,0 +1,75 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validatePluginObject = validatePluginObject; + +var _optionAssertions = require("./option-assertions"); + +const VALIDATORS = { + name: _optionAssertions.assertString, + manipulateOptions: _optionAssertions.assertFunction, + pre: _optionAssertions.assertFunction, + post: _optionAssertions.assertFunction, + inherits: _optionAssertions.assertFunction, + visitor: assertVisitorMap, + parserOverride: _optionAssertions.assertFunction, + generatorOverride: _optionAssertions.assertFunction +}; + +function assertVisitorMap(loc, value) { + const obj = (0, _optionAssertions.assertObject)(loc, value); + + if (obj) { + Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop])); + + if (obj.enter || obj.exit) { + throw new Error(`${(0, _optionAssertions.msg)(loc)} cannot contain catch-all "enter" or "exit" handlers. Please target individual nodes.`); + } + } + + return obj; +} + +function assertVisitorHandler(key, value) { + if (value && typeof value === "object") { + Object.keys(value).forEach(handler => { + if (handler !== "enter" && handler !== "exit") { + throw new Error(`.visitor["${key}"] may only have .enter and/or .exit handlers.`); + } + }); + } else if (typeof value !== "function") { + throw new Error(`.visitor["${key}"] must be a function`); + } + + return value; +} + +function validatePluginObject(obj) { + const rootPath = { + type: "root", + source: "plugin" + }; + Object.keys(obj).forEach(key => { + const validator = VALIDATORS[key]; + + if (validator) { + const optLoc = { + type: "option", + name: key, + parent: rootPath + }; + validator(optLoc, obj[key]); + } else { + const invalidPluginPropertyError = new Error(`.${key} is not a valid Plugin property`); + invalidPluginPropertyError.code = "BABEL_UNKNOWN_PLUGIN_PROPERTY"; + throw invalidPluginPropertyError; + } + }); + return obj; +} + +0 && 0; + +//# sourceMappingURL=plugins.js.map diff --git a/node_modules/@babel/core/lib/config/validation/plugins.js.map b/node_modules/@babel/core/lib/config/validation/plugins.js.map new file mode 100644 index 0000000..50121cd --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/plugins.js.map @@ -0,0 +1 @@ +{"version":3,"names":["VALIDATORS","name","assertString","manipulateOptions","assertFunction","pre","post","inherits","visitor","assertVisitorMap","parserOverride","generatorOverride","loc","value","obj","assertObject","Object","keys","forEach","prop","assertVisitorHandler","enter","exit","Error","msg","key","handler","validatePluginObject","rootPath","type","source","validator","optLoc","parent","invalidPluginPropertyError","code"],"sources":["../../../src/config/validation/plugins.ts"],"sourcesContent":["import {\n assertString,\n assertFunction,\n assertObject,\n msg,\n} from \"./option-assertions\";\n\nimport type {\n ValidatorSet,\n Validator,\n OptionPath,\n RootPath,\n} from \"./option-assertions\";\nimport type { ParserOptions } from \"@babel/parser\";\nimport type { Visitor } from \"@babel/traverse\";\nimport type { ValidatedOptions } from \"./options\";\nimport type { File, PluginPass } from \"../../index\";\n\n// Note: The casts here are just meant to be static assertions to make sure\n// that the assertion functions actually assert that the value's type matches\n// the declared types.\nconst VALIDATORS: ValidatorSet = {\n name: assertString as Validator,\n manipulateOptions: assertFunction as Validator<\n PluginObject[\"manipulateOptions\"]\n >,\n pre: assertFunction as Validator,\n post: assertFunction as Validator,\n inherits: assertFunction as Validator,\n visitor: assertVisitorMap as Validator,\n\n parserOverride: assertFunction as Validator,\n generatorOverride: assertFunction as Validator<\n PluginObject[\"generatorOverride\"]\n >,\n};\n\nfunction assertVisitorMap(loc: OptionPath, value: unknown): Visitor {\n const obj = assertObject(loc, value);\n if (obj) {\n Object.keys(obj).forEach(prop => assertVisitorHandler(prop, obj[prop]));\n\n if (obj.enter || obj.exit) {\n throw new Error(\n `${msg(\n loc,\n )} cannot contain catch-all \"enter\" or \"exit\" handlers. Please target individual nodes.`,\n );\n }\n }\n return obj as Visitor;\n}\n\nfunction assertVisitorHandler(\n key: string,\n value: unknown,\n): VisitorHandler | void {\n if (value && typeof value === \"object\") {\n Object.keys(value).forEach((handler: string) => {\n if (handler !== \"enter\" && handler !== \"exit\") {\n throw new Error(\n `.visitor[\"${key}\"] may only have .enter and/or .exit handlers.`,\n );\n }\n });\n } else if (typeof value !== \"function\") {\n throw new Error(`.visitor[\"${key}\"] must be a function`);\n }\n\n return value as any;\n}\n\ntype VisitorHandler =\n | Function\n | {\n enter?: Function;\n exit?: Function;\n };\n\nexport type PluginObject = {\n name?: string;\n manipulateOptions?: (\n options: ValidatedOptions,\n parserOpts: ParserOptions,\n ) => void;\n pre?: (this: S, file: File) => void;\n post?: (this: S, file: File) => void;\n inherits?: Function;\n visitor?: Visitor;\n parserOverride?: Function;\n generatorOverride?: Function;\n};\n\nexport function validatePluginObject(obj: {\n [key: string]: unknown;\n}): PluginObject {\n const rootPath: RootPath = {\n type: \"root\",\n source: \"plugin\",\n };\n Object.keys(obj).forEach((key: string) => {\n const validator = VALIDATORS[key];\n\n if (validator) {\n const optLoc: OptionPath = {\n type: \"option\",\n name: key,\n parent: rootPath,\n };\n validator(optLoc, obj[key]);\n } else {\n const invalidPluginPropertyError = new Error(\n `.${key} is not a valid Plugin property`,\n );\n // @ts-expect-error todo(flow->ts) consider additing BabelConfigError with code field\n invalidPluginPropertyError.code = \"BABEL_UNKNOWN_PLUGIN_PROPERTY\";\n throw invalidPluginPropertyError;\n }\n });\n\n return obj as any;\n}\n"],"mappings":";;;;;;;AAAA;;AAqBA,MAAMA,UAAwB,GAAG;EAC/BC,IAAI,EAAEC,8BADyB;EAE/BC,iBAAiB,EAAEC,gCAFY;EAK/BC,GAAG,EAAED,gCAL0B;EAM/BE,IAAI,EAAEF,gCANyB;EAO/BG,QAAQ,EAAEH,gCAPqB;EAQ/BI,OAAO,EAAEC,gBARsB;EAU/BC,cAAc,EAAEN,gCAVe;EAW/BO,iBAAiB,EAAEP;AAXY,CAAjC;;AAgBA,SAASK,gBAAT,CAA0BG,GAA1B,EAA2CC,KAA3C,EAAoE;EAClE,MAAMC,GAAG,GAAG,IAAAC,8BAAA,EAAaH,GAAb,EAAkBC,KAAlB,CAAZ;;EACA,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G,SAAS,CAACC,MAAD,EAASlB,GAAG,CAACW,GAAD,CAAZ,CAAT;IACD,CAPD,MAOO;MACL,MAAMS,0BAA0B,GAAG,IAAIX,KAAJ,CAChC,IAAGE,GAAI,iCADyB,CAAnC;MAIAS,0BAA0B,CAACC,IAA3B,GAAkC,+BAAlC;MACA,MAAMD,0BAAN;IACD;EACF,CAlBD;EAoBA,OAAOpB,GAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/config/validation/removed.js b/node_modules/@babel/core/lib/config/validation/removed.js new file mode 100644 index 0000000..57270ea --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/removed.js @@ -0,0 +1,69 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; +var _default = { + auxiliaryComment: { + message: "Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`" + }, + blacklist: { + message: "Put the specific transforms you want in the `plugins` option" + }, + breakConfig: { + message: "This is not a necessary option in Babel 6" + }, + experimental: { + message: "Put the specific transforms you want in the `plugins` option" + }, + externalHelpers: { + message: "Use the `external-helpers` plugin instead. " + "Check out http://babeljs.io/docs/plugins/external-helpers/" + }, + extra: { + message: "" + }, + jsxPragma: { + message: "use the `pragma` option in the `react-jsx` plugin. " + "Check out http://babeljs.io/docs/plugins/transform-react-jsx/" + }, + loose: { + message: "Specify the `loose` option for the relevant plugin you are using " + "or use a preset that sets the option." + }, + metadataUsedHelpers: { + message: "Not required anymore as this is enabled by default" + }, + modules: { + message: "Use the corresponding module transform plugin in the `plugins` option. " + "Check out http://babeljs.io/docs/plugins/#modules" + }, + nonStandard: { + message: "Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. " + "Also check out the react preset http://babeljs.io/docs/plugins/preset-react/" + }, + optional: { + message: "Put the specific transforms you want in the `plugins` option" + }, + sourceMapName: { + message: "The `sourceMapName` option has been removed because it makes more sense for the " + "tooling that calls Babel to assign `map.file` themselves." + }, + stage: { + message: "Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets" + }, + whitelist: { + message: "Put the specific transforms you want in the `plugins` option" + }, + resolveModuleSource: { + version: 6, + message: "Use `babel-plugin-module-resolver@3`'s 'resolvePath' options" + }, + metadata: { + version: 6, + message: "Generated plugin metadata is always included in the output result" + }, + sourceMapTarget: { + version: 6, + message: "The `sourceMapTarget` option has been removed because it makes more sense for the tooling " + "that calls Babel to assign `map.file` themselves." + } +}; +exports.default = _default; +0 && 0; + +//# sourceMappingURL=removed.js.map diff --git a/node_modules/@babel/core/lib/config/validation/removed.js.map b/node_modules/@babel/core/lib/config/validation/removed.js.map new file mode 100644 index 0000000..dc7836d --- /dev/null +++ b/node_modules/@babel/core/lib/config/validation/removed.js.map @@ -0,0 +1 @@ +{"version":3,"names":["auxiliaryComment","message","blacklist","breakConfig","experimental","externalHelpers","extra","jsxPragma","loose","metadataUsedHelpers","modules","nonStandard","optional","sourceMapName","stage","whitelist","resolveModuleSource","version","metadata","sourceMapTarget"],"sources":["../../../src/config/validation/removed.ts"],"sourcesContent":["export default {\n auxiliaryComment: {\n message: \"Use `auxiliaryCommentBefore` or `auxiliaryCommentAfter`\",\n },\n blacklist: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n breakConfig: {\n message: \"This is not a necessary option in Babel 6\",\n },\n experimental: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n externalHelpers: {\n message:\n \"Use the `external-helpers` plugin instead. \" +\n \"Check out http://babeljs.io/docs/plugins/external-helpers/\",\n },\n extra: {\n message: \"\",\n },\n jsxPragma: {\n message:\n \"use the `pragma` option in the `react-jsx` plugin. \" +\n \"Check out http://babeljs.io/docs/plugins/transform-react-jsx/\",\n },\n loose: {\n message:\n \"Specify the `loose` option for the relevant plugin you are using \" +\n \"or use a preset that sets the option.\",\n },\n metadataUsedHelpers: {\n message: \"Not required anymore as this is enabled by default\",\n },\n modules: {\n message:\n \"Use the corresponding module transform plugin in the `plugins` option. \" +\n \"Check out http://babeljs.io/docs/plugins/#modules\",\n },\n nonStandard: {\n message:\n \"Use the `react-jsx` and `flow-strip-types` plugins to support JSX and Flow. \" +\n \"Also check out the react preset http://babeljs.io/docs/plugins/preset-react/\",\n },\n optional: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n sourceMapName: {\n message:\n \"The `sourceMapName` option has been removed because it makes more sense for the \" +\n \"tooling that calls Babel to assign `map.file` themselves.\",\n },\n stage: {\n message:\n \"Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets\",\n },\n whitelist: {\n message: \"Put the specific transforms you want in the `plugins` option\",\n },\n\n resolveModuleSource: {\n version: 6,\n message: \"Use `babel-plugin-module-resolver@3`'s 'resolvePath' options\",\n },\n metadata: {\n version: 6,\n message:\n \"Generated plugin metadata is always included in the output result\",\n },\n sourceMapTarget: {\n version: 6,\n message:\n \"The `sourceMapTarget` option has been removed because it makes more sense for the tooling \" +\n \"that calls Babel to assign `map.file` themselves.\",\n },\n} as { [name: string]: { version?: number; message: string } };\n"],"mappings":";;;;;;eAAe;EACbA,gBAAgB,EAAE;IAChBC,OAAO,EAAE;EADO,CADL;EAIbC,SAAS,EAAE;IACTD,OAAO,EAAE;EADA,CAJE;EAObE,WAAW,EAAE;IACXF,OAAO,EAAE;EADE,CAPA;EAUbG,YAAY,EAAE;IACZH,OAAO,EAAE;EADG,CAVD;EAabI,eAAe,EAAE;IACfJ,OAAO,EACL,gDACA;EAHa,CAbJ;EAkBbK,KAAK,EAAE;IACLL,OAAO,EAAE;EADJ,CAlBM;EAqBbM,SAAS,EAAE;IACTN,OAAO,EACL,wDACA;EAHO,CArBE;EA0BbO,KAAK,EAAE;IACLP,OAAO,EACL,sEACA;EAHG,CA1BM;EA+BbQ,mBAAmB,EAAE;IACnBR,OAAO,EAAE;EADU,CA/BR;EAkCbS,OAAO,EAAE;IACPT,OAAO,EACL,4EACA;EAHK,CAlCI;EAuCbU,WAAW,EAAE;IACXV,OAAO,EACL,iFACA;EAHS,CAvCA;EA4CbW,QAAQ,EAAE;IACRX,OAAO,EAAE;EADD,CA5CG;EA+CbY,aAAa,EAAE;IACbZ,OAAO,EACL,qFACA;EAHW,CA/CF;EAoDba,KAAK,EAAE;IACLb,OAAO,EACL;EAFG,CApDM;EAwDbc,SAAS,EAAE;IACTd,OAAO,EAAE;EADA,CAxDE;EA4Dbe,mBAAmB,EAAE;IACnBC,OAAO,EAAE,CADU;IAEnBhB,OAAO,EAAE;EAFU,CA5DR;EAgEbiB,QAAQ,EAAE;IACRD,OAAO,EAAE,CADD;IAERhB,OAAO,EACL;EAHM,CAhEG;EAqEbkB,eAAe,EAAE;IACfF,OAAO,EAAE,CADM;IAEfhB,OAAO,EACL,+FACA;EAJa;AArEJ,C"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/errors/config-error.js b/node_modules/@babel/core/lib/errors/config-error.js new file mode 100644 index 0000000..ecab2dc --- /dev/null +++ b/node_modules/@babel/core/lib/errors/config-error.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _rewriteStackTrace = require("./rewrite-stack-trace"); + +class ConfigError extends Error { + constructor(message, filename) { + super(message); + (0, _rewriteStackTrace.expectedError)(this); + if (filename) (0, _rewriteStackTrace.injcectVirtualStackFrame)(this, filename); + } + +} + +exports.default = ConfigError; +0 && 0; + +//# sourceMappingURL=config-error.js.map diff --git a/node_modules/@babel/core/lib/errors/config-error.js.map b/node_modules/@babel/core/lib/errors/config-error.js.map new file mode 100644 index 0000000..864e8b7 --- /dev/null +++ b/node_modules/@babel/core/lib/errors/config-error.js.map @@ -0,0 +1 @@ +{"version":3,"names":["ConfigError","Error","constructor","message","filename","expectedError","injcectVirtualStackFrame"],"sources":["../../src/errors/config-error.ts"],"sourcesContent":["import { injcectVirtualStackFrame, expectedError } from \"./rewrite-stack-trace\";\n\nexport default class ConfigError extends Error {\n constructor(message: string, filename?: string) {\n super(message);\n expectedError(this);\n if (filename) injcectVirtualStackFrame(this, filename);\n }\n}\n"],"mappings":";;;;;;;AAAA;;AAEe,MAAMA,WAAN,SAA0BC,KAA1B,CAAgC;EAC7CC,WAAW,CAACC,OAAD,EAAkBC,QAAlB,EAAqC;IAC9C,MAAMD,OAAN;IACA,IAAAE,gCAAA,EAAc,IAAd;IACA,IAAID,QAAJ,EAAc,IAAAE,2CAAA,EAAyB,IAAzB,EAA+BF,QAA/B;EACf;;AAL4C"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js b/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js new file mode 100644 index 0000000..c193a63 --- /dev/null +++ b/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js @@ -0,0 +1,111 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.beginHiddenCallStack = beginHiddenCallStack; +exports.endHiddenCallStack = endHiddenCallStack; +exports.expectedError = expectedError; +exports.injcectVirtualStackFrame = injcectVirtualStackFrame; +const ErrorToString = Function.call.bind(Error.prototype.toString); +const SUPPORTED = !!Error.captureStackTrace; +const START_HIDNG = "startHiding - secret - don't use this - v1"; +const STOP_HIDNG = "stopHiding - secret - don't use this - v1"; +const expectedErrors = new WeakSet(); +const virtualFrames = new WeakMap(); + +function CallSite(filename) { + return Object.create({ + isNative: () => false, + isConstructor: () => false, + isToplevel: () => true, + getFileName: () => filename, + getLineNumber: () => undefined, + getColumnNumber: () => undefined, + getFunctionName: () => undefined, + getMethodName: () => undefined, + getTypeName: () => undefined, + toString: () => filename + }); +} + +function injcectVirtualStackFrame(error, filename) { + if (!SUPPORTED) return; + let frames = virtualFrames.get(error); + if (!frames) virtualFrames.set(error, frames = []); + frames.push(CallSite(filename)); + return error; +} + +function expectedError(error) { + if (!SUPPORTED) return; + expectedErrors.add(error); + return error; +} + +function beginHiddenCallStack(fn) { + if (!SUPPORTED) return fn; + return Object.defineProperty(function (...args) { + setupPrepareStackTrace(); + return fn(...args); + }, "name", { + value: STOP_HIDNG + }); +} + +function endHiddenCallStack(fn) { + if (!SUPPORTED) return fn; + return Object.defineProperty(function (...args) { + return fn(...args); + }, "name", { + value: START_HIDNG + }); +} + +function setupPrepareStackTrace() { + setupPrepareStackTrace = () => {}; + + const { + prepareStackTrace = defaultPrepareStackTrace + } = Error; + const MIN_STACK_TRACE_LIMIT = 50; + Error.stackTraceLimit && (Error.stackTraceLimit = Math.max(Error.stackTraceLimit, MIN_STACK_TRACE_LIMIT)); + + Error.prepareStackTrace = function stackTraceRewriter(err, trace) { + let newTrace = []; + const isExpected = expectedErrors.has(err); + let status = isExpected ? "hiding" : "unknown"; + + for (let i = 0; i < trace.length; i++) { + const name = trace[i].getFunctionName(); + + if (name === START_HIDNG) { + status = "hiding"; + } else if (name === STOP_HIDNG) { + if (status === "hiding") { + status = "showing"; + + if (virtualFrames.has(err)) { + newTrace.unshift(...virtualFrames.get(err)); + } + } else if (status === "unknown") { + newTrace = trace; + break; + } + } else if (status !== "hiding") { + newTrace.push(trace[i]); + } + } + + return prepareStackTrace(err, newTrace); + }; +} + +function defaultPrepareStackTrace(err, trace) { + if (trace.length === 0) return ErrorToString(err); + return `${ErrorToString(err)}\n at ${trace.join("\n at ")}`; +} + +0 && 0; + +//# sourceMappingURL=rewrite-stack-trace.js.map diff --git a/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js.map b/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js.map new file mode 100644 index 0000000..408e8fa --- /dev/null +++ b/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js.map @@ -0,0 +1 @@ +{"version":3,"names":["ErrorToString","Function","call","bind","Error","prototype","toString","SUPPORTED","captureStackTrace","START_HIDNG","STOP_HIDNG","expectedErrors","WeakSet","virtualFrames","WeakMap","CallSite","filename","Object","create","isNative","isConstructor","isToplevel","getFileName","getLineNumber","undefined","getColumnNumber","getFunctionName","getMethodName","getTypeName","injcectVirtualStackFrame","error","frames","get","set","push","expectedError","add","beginHiddenCallStack","fn","defineProperty","args","setupPrepareStackTrace","value","endHiddenCallStack","prepareStackTrace","defaultPrepareStackTrace","MIN_STACK_TRACE_LIMIT","stackTraceLimit","Math","max","stackTraceRewriter","err","trace","newTrace","isExpected","has","status","i","length","name","unshift","join"],"sources":["../../src/errors/rewrite-stack-trace.ts"],"sourcesContent":["/**\n * This file uses the iternal V8 Stack Trace API (https://v8.dev/docs/stack-trace-api)\n * to provide utilities to rewrite the stack trace.\n * When this API is not present, all the functions in this file become noops.\n *\n * beginHiddenCallStack(fn) and endHiddenCallStack(fn) wrap their parameter to\n * mark an hidden portion of the stack trace. The function passed to\n * beginHiddenCallStack is the first hidden function, while the function passed\n * to endHiddenCallStack is the first shown function.\n *\n * When an error is thrown _outside_ of the hidden zone, everything between\n * beginHiddenCallStack and endHiddenCallStack will not be shown.\n * If an error is thrown _inside_ the hidden zone, then the whole stack trace\n * will be visible: this is to avoid hiding real bugs.\n * However, if an error inside the hidden zone is expected, it can be marked\n * with the expectedError(error) function to keep the hidden frames hidden.\n *\n * Consider this call stack (the outer function is the bottom one):\n *\n * 1. a()\n * 2. endHiddenCallStack(b)()\n * 3. c()\n * 4. beginHiddenCallStack(d)()\n * 5. e()\n * 6. f()\n *\n * - If a() throws an error, then its shown call stack will be \"a, b, e, f\"\n * - If b() throws an error, then its shown call stack will be \"b, e, f\"\n * - If c() throws an expected error, then its shown call stack will be \"e, f\"\n * - If c() throws an unexpected error, then its shown call stack will be \"c, d, e, f\"\n * - If d() throws an expected error, then its shown call stack will be \"e, f\"\n * - If d() throws an unexpected error, then its shown call stack will be \"d, e, f\"\n * - If e() throws an error, then its shown call stack will be \"e, f\"\n *\n * Additionally, an error can inject additional \"virtual\" stack frames using the\n * injcectVirtualStackFrame(error, filename) function: those are injected as a\n * replacement of the hidden frames.\n * In the example above, if we called injcectVirtualStackFrame(err, \"h\") and\n * injcectVirtualStackFrame(err, \"i\") on the expected error thrown by c(), its\n * shown call stack would have been \"h, i, e, f\".\n * This can be useful, for example, to report config validation errors as if they\n * were directly thrown in the config file.\n */\n\nconst ErrorToString = Function.call.bind(Error.prototype.toString);\n\nconst SUPPORTED = !!Error.captureStackTrace;\n\nconst START_HIDNG = \"startHiding - secret - don't use this - v1\";\nconst STOP_HIDNG = \"stopHiding - secret - don't use this - v1\";\n\ntype CallSite = Parameters[1][number];\n\nconst expectedErrors = new WeakSet();\nconst virtualFrames = new WeakMap();\n\nfunction CallSite(filename: string): CallSite {\n // We need to use a prototype otherwise it breaks source-map-support's internals\n return Object.create({\n isNative: () => false,\n isConstructor: () => false,\n isToplevel: () => true,\n getFileName: () => filename,\n getLineNumber: () => undefined,\n getColumnNumber: () => undefined,\n getFunctionName: () => undefined,\n getMethodName: () => undefined,\n getTypeName: () => undefined,\n toString: () => filename,\n } as CallSite);\n}\n\nexport function injcectVirtualStackFrame(error: Error, filename: string) {\n if (!SUPPORTED) return;\n\n let frames = virtualFrames.get(error);\n if (!frames) virtualFrames.set(error, (frames = []));\n frames.push(CallSite(filename));\n\n return error;\n}\n\nexport function expectedError(error: Error) {\n if (!SUPPORTED) return;\n expectedErrors.add(error);\n return error;\n}\n\nexport function beginHiddenCallStack(\n fn: (...args: A) => R,\n) {\n if (!SUPPORTED) return fn;\n\n return Object.defineProperty(\n function (...args: A) {\n setupPrepareStackTrace();\n return fn(...args);\n },\n \"name\",\n { value: STOP_HIDNG },\n );\n}\n\nexport function endHiddenCallStack(\n fn: (...args: A) => R,\n) {\n if (!SUPPORTED) return fn;\n\n return Object.defineProperty(\n function (...args: A) {\n return fn(...args);\n },\n \"name\",\n { value: START_HIDNG },\n );\n}\n\nfunction setupPrepareStackTrace() {\n // @ts-expect-error This function is a singleton\n // eslint-disable-next-line no-func-assign\n setupPrepareStackTrace = () => {};\n\n const { prepareStackTrace = defaultPrepareStackTrace } = Error;\n\n // We add some extra frames to Error.stackTraceLimit, so that we can\n // always show some useful frames even after deleting ours.\n // STACK_TRACE_LIMIT_DELTA should be around the maximum expected number\n // of internal frames, and not too big because capturing the stack trace\n // is slow (this is why Error.stackTraceLimit does not default to Infinity!).\n // Increase it if needed.\n // However, we only do it if the user did not explicitly set it to 0.\n const MIN_STACK_TRACE_LIMIT = 50;\n Error.stackTraceLimit &&= Math.max(\n Error.stackTraceLimit,\n MIN_STACK_TRACE_LIMIT,\n );\n\n Error.prepareStackTrace = function stackTraceRewriter(err, trace) {\n let newTrace = [];\n\n const isExpected = expectedErrors.has(err);\n let status: \"showing\" | \"hiding\" | \"unknown\" = isExpected\n ? \"hiding\"\n : \"unknown\";\n for (let i = 0; i < trace.length; i++) {\n const name = trace[i].getFunctionName();\n if (name === START_HIDNG) {\n status = \"hiding\";\n } else if (name === STOP_HIDNG) {\n if (status === \"hiding\") {\n status = \"showing\";\n if (virtualFrames.has(err)) {\n newTrace.unshift(...virtualFrames.get(err));\n }\n } else if (status === \"unknown\") {\n // Unexpected internal error, show the full stack trace\n newTrace = trace;\n break;\n }\n } else if (status !== \"hiding\") {\n newTrace.push(trace[i]);\n }\n }\n\n return prepareStackTrace(err, newTrace);\n };\n}\n\nfunction defaultPrepareStackTrace(err: Error, trace: CallSite[]) {\n if (trace.length === 0) return ErrorToString(err);\n return `${ErrorToString(err)}\\n at ${trace.join(\"\\n at \")}`;\n}\n"],"mappings":";;;;;;;;;AA4CA,MAAMA,aAAa,GAAGC,QAAQ,CAACC,IAAT,CAAcC,IAAd,CAAmBC,KAAK,CAACC,SAAN,CAAgBC,QAAnC,CAAtB;AAEA,MAAMC,SAAS,GAAG,CAAC,CAACH,KAAK,CAACI,iBAA1B;AAEA,MAAMC,WAAW,GAAG,4CAApB;AACA,MAAMC,UAAU,GAAG,2CAAnB;AAIA,MAAMC,cAAc,GAAG,IAAIC,OAAJ,EAAvB;AACA,MAAMC,aAAa,GAAG,IAAIC,OAAJ,EAAtB;;AAEA,SAASC,QAAT,CAAkBC,QAAlB,EAA8C;EAE5C,OAAOC,MAAM,CAACC,MAAP,CAAc;IACnBC,QAAQ,EAAE,MAAM,KADG;IAEnBC,aAAa,EAAE,MAAM,KAFF;IAGnBC,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;MACF,CAXM,MAWA,IAAII,MAAM,KAAK,QAAf,EAAyB;QAC9BH,QAAQ,CAACnB,IAAT,CAAckB,KAAK,CAACK,CAAD,CAAnB;MACD;IACF;;IAED,OAAOb,iBAAiB,CAACO,GAAD,EAAME,QAAN,CAAxB;EACD,CA5BD;AA6BD;;AAED,SAASR,wBAAT,CAAkCM,GAAlC,EAA8CC,KAA9C,EAAiE;EAC/D,IAAIA,KAAK,CAACM,MAAN,KAAiB,CAArB,EAAwB,OAAO1D,aAAa,CAACmD,GAAD,CAApB;EACxB,OAAQ,GAAEnD,aAAa,CAACmD,GAAD,CAAM,YAAWC,KAAK,CAACS,IAAN,CAAW,WAAX,CAAwB,EAAhE;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/gensync-utils/async.js b/node_modules/@babel/core/lib/gensync-utils/async.js new file mode 100644 index 0000000..724b0fd --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/async.js @@ -0,0 +1,116 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.forwardAsync = forwardAsync; +exports.isAsync = void 0; +exports.isThenable = isThenable; +exports.maybeAsync = maybeAsync; +exports.waitFor = exports.onFirstPause = void 0; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +const runGenerator = _gensync()(function* (item) { + return yield* item; +}); + +const isAsync = _gensync()({ + sync: () => false, + errback: cb => cb(null, true) +}); + +exports.isAsync = isAsync; + +function maybeAsync(fn, message) { + return _gensync()({ + sync(...args) { + const result = fn.apply(this, args); + if (isThenable(result)) throw new Error(message); + return result; + }, + + async(...args) { + return Promise.resolve(fn.apply(this, args)); + } + + }); +} + +const withKind = _gensync()({ + sync: cb => cb("sync"), + async: function () { + var _ref = _asyncToGenerator(function* (cb) { + return cb("async"); + }); + + return function async(_x) { + return _ref.apply(this, arguments); + }; + }() +}); + +function forwardAsync(action, cb) { + const g = _gensync()(action); + + return withKind(kind => { + const adapted = g[kind]; + return cb(adapted); + }); +} + +const onFirstPause = _gensync()({ + name: "onFirstPause", + arity: 2, + sync: function (item) { + return runGenerator.sync(item); + }, + errback: function (item, firstPause, cb) { + let completed = false; + runGenerator.errback(item, (err, value) => { + completed = true; + cb(err, value); + }); + + if (!completed) { + firstPause(); + } + } +}); + +exports.onFirstPause = onFirstPause; + +const waitFor = _gensync()({ + sync: x => x, + async: function () { + var _ref2 = _asyncToGenerator(function* (x) { + return x; + }); + + return function async(_x2) { + return _ref2.apply(this, arguments); + }; + }() +}); + +exports.waitFor = waitFor; + +function isThenable(val) { + return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; +} + +0 && 0; + +//# sourceMappingURL=async.js.map diff --git a/node_modules/@babel/core/lib/gensync-utils/async.js.map b/node_modules/@babel/core/lib/gensync-utils/async.js.map new file mode 100644 index 0000000..330e0ee --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/async.js.map @@ -0,0 +1 @@ +{"version":3,"names":["runGenerator","gensync","item","isAsync","sync","errback","cb","maybeAsync","fn","message","args","result","apply","isThenable","Error","async","Promise","resolve","withKind","forwardAsync","action","g","kind","adapted","onFirstPause","name","arity","firstPause","completed","err","value","waitFor","x","val","then"],"sources":["../../src/gensync-utils/async.ts"],"sourcesContent":["import gensync, { type Gensync, type Handler, type Callback } from \"gensync\";\n\ntype MaybePromise = T | Promise;\n\nconst runGenerator: {\n sync(gen: Handler): Return;\n async(gen: Handler): Promise;\n errback(gen: Handler, cb: Callback): void;\n} = gensync(function* (item: Handler): Handler {\n return yield* item;\n});\n\n// This Gensync returns true if the current execution context is\n// asynchronous, otherwise it returns false.\nexport const isAsync = gensync({\n sync: () => false,\n errback: cb => cb(null, true),\n});\n\n// This function wraps any functions (which could be either synchronous or\n// asynchronous) with a Gensync. If the wrapped function returns a promise\n// but the current execution context is synchronous, it will throw the\n// provided error.\n// This is used to handle user-provided functions which could be asynchronous.\nexport function maybeAsync(\n fn: (...args: Args) => Return,\n message: string,\n): Gensync {\n return gensync({\n sync(...args) {\n const result = fn.apply(this, args) as Return;\n if (isThenable(result)) throw new Error(message);\n return result;\n },\n async(...args) {\n return Promise.resolve(fn.apply(this, args));\n },\n });\n}\n\nconst withKind = gensync({\n sync: cb => cb(\"sync\"),\n async: async cb => cb(\"async\"),\n}) as (cb: (kind: \"sync\" | \"async\") => MaybePromise) => Handler;\n\n// This function wraps a generator (or a Gensync) into another function which,\n// when called, will run the provided generator in a sync or async way, depending\n// on the execution context where this forwardAsync function is called.\n// This is useful, for example, when passing a callback to a function which isn't\n// aware of gensync, but it only knows about synchronous and asynchronous functions.\n// An example is cache.using, which being exposed to the user must be as simple as\n// possible:\n// yield* forwardAsync(gensyncFn, wrappedFn =>\n// cache.using(x => {\n// // Here we don't know about gensync. wrappedFn is a\n// // normal sync or async function\n// return wrappedFn(x);\n// })\n// )\nexport function forwardAsync(\n action: (...args: Args) => Handler,\n cb: (\n adapted: (...args: Args) => MaybePromise,\n ) => MaybePromise,\n): Handler {\n const g = gensync(action);\n return withKind(kind => {\n const adapted = g[kind];\n return cb(adapted);\n });\n}\n\n// If the given generator is executed asynchronously, the first time that it\n// is paused (i.e. When it yields a gensync generator which can't be run\n// synchronously), call the \"firstPause\" callback.\nexport const onFirstPause = gensync<\n [gen: Handler, firstPause: () => void],\n unknown\n>({\n name: \"onFirstPause\",\n arity: 2,\n sync: function (item) {\n return runGenerator.sync(item);\n },\n errback: function (item, firstPause, cb) {\n let completed = false;\n\n runGenerator.errback(item, (err, value) => {\n completed = true;\n cb(err, value);\n });\n\n if (!completed) {\n firstPause();\n }\n },\n}) as (gen: Handler, firstPause: () => void) => Handler;\n\n// Wait for the given promise to be resolved\nexport const waitFor = gensync({\n sync: x => x,\n async: async x => x,\n}) as (p: T | Promise) => Handler;\n\nexport function isThenable(val: any): val is PromiseLike {\n return (\n !!val &&\n (typeof val === \"object\" || typeof val === \"function\") &&\n !!val.then &&\n typeof val.then === \"function\"\n );\n}\n"],"mappings":";;;;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;;;;;AAIA,MAAMA,YAIL,GAAGC,UAAA,CAAQ,WAAWC,IAAX,EAA6C;EACvD,OAAO,OAAOA,IAAd;AACD,CAFG,CAJJ;;AAUO,MAAMC,OAAO,GAAGF,UAAA,CAAQ;EAC7BG,IAAI,EAAE,MAAM,KADiB;EAE7BC,OAAO,EAAEC,EAAE,IAAIA,EAAE,CAAC,IAAD,EAAO,IAAP;AAFY,CAAR,CAAhB;;;;AAUA,SAASC,UAAT,CACLC,EADK,EAELC,OAFK,EAGkB;EACvB,OAAOR,UAAA,CAAQ;IACbG,IAAI,CAAC,GAAGM,IAAJ,EAAU;MACZ,MAAMC,MAAM,GAAGH,EAAE,CAACI,KAAH,CAAS,IAAT,EAAeF,IAAf,CAAf;MACA,IAAIG,UAAU,CAACF,MAAD,CAAd,EAAwB,MAAM,IAAIG,KAAJ,CAAUL,OAAV,CAAN;MACxB,OAAOE,MAAP;IACD,CALY;;IAMbI,KAAK,CAAC,GAAGL,IAAJ,EAAU;MACb,OAAOM,OAAO,CAACC,OAAR,CAAgBT,EAAE,CAACI,KAAH,CAAS,IAAT,EAAeF,IAAf,CAAhB,CAAP;IACD;;EARY,CAAR,CAAP;AAUD;;AAED,MAAMQ,QAAQ,GAAGjB,UAAA,CAAQ;EACvBG,IAAI,EAAEE,EAAE,IAAIA,EAAE,CAAC,MAAD,CADS;EAEvBS,KAAK;IAAA,6BAAE,WAAMT,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AAe,UAD3C,KAEA,CAAC,CAACA,GAAG,CAACC,IAFN,IAGA,OAAOD,GAAG,CAACC,IAAX,KAAoB,UAJtB;AAMD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/gensync-utils/fs.js b/node_modules/@babel/core/lib/gensync-utils/fs.js new file mode 100644 index 0000000..31f49ae --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/fs.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.stat = exports.readFile = void 0; + +function _fs() { + const data = require("fs"); + + _fs = function () { + return data; + }; + + return data; +} + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +const readFile = _gensync()({ + sync: _fs().readFileSync, + errback: _fs().readFile +}); + +exports.readFile = readFile; + +const stat = _gensync()({ + sync: _fs().statSync, + errback: _fs().stat +}); + +exports.stat = stat; +0 && 0; + +//# sourceMappingURL=fs.js.map diff --git a/node_modules/@babel/core/lib/gensync-utils/fs.js.map b/node_modules/@babel/core/lib/gensync-utils/fs.js.map new file mode 100644 index 0000000..cc32eb1 --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/fs.js.map @@ -0,0 +1 @@ +{"version":3,"names":["readFile","gensync","sync","fs","readFileSync","errback","stat","statSync"],"sources":["../../src/gensync-utils/fs.ts"],"sourcesContent":["import fs from \"fs\";\nimport gensync from \"gensync\";\n\nexport const readFile = gensync<[filepath: string, encoding: \"utf8\"], string>({\n sync: fs.readFileSync,\n errback: fs.readFile,\n});\n\nexport const stat = gensync({\n sync: fs.statSync,\n errback: fs.stat,\n});\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEO,MAAMA,QAAQ,GAAGC,UAAA,CAAsD;EAC5EC,IAAI,EAAEC,KAAA,CAAGC,YADmE;EAE5EC,OAAO,EAAEF,KAAA,CAAGH;AAFgE,CAAtD,CAAjB;;;;AAKA,MAAMM,IAAI,GAAGL,UAAA,CAAQ;EAC1BC,IAAI,EAAEC,KAAA,CAAGI,QADiB;EAE1BF,OAAO,EAAEF,KAAA,CAAGG;AAFc,CAAR,CAAb"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/gensync-utils/functional.js b/node_modules/@babel/core/lib/gensync-utils/functional.js new file mode 100644 index 0000000..a80eaf7 --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/functional.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.once = once; + +var _async = require("./async"); + +function once(fn) { + let result; + let resultP; + return function* () { + if (result) return result; + if (!(yield* (0, _async.isAsync)())) return result = yield* fn(); + if (resultP) return yield* (0, _async.waitFor)(resultP); + let resolve, reject; + resultP = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + + try { + result = yield* fn(); + resultP = null; + resolve(result); + return result; + } catch (error) { + reject(error); + throw error; + } + }; +} + +0 && 0; + +//# sourceMappingURL=functional.js.map diff --git a/node_modules/@babel/core/lib/gensync-utils/functional.js.map b/node_modules/@babel/core/lib/gensync-utils/functional.js.map new file mode 100644 index 0000000..0db106a --- /dev/null +++ b/node_modules/@babel/core/lib/gensync-utils/functional.js.map @@ -0,0 +1 @@ +{"version":3,"names":["once","fn","result","resultP","isAsync","waitFor","resolve","reject","Promise","res","rej","error"],"sources":["../../src/gensync-utils/functional.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\n\nimport { isAsync, waitFor } from \"./async\";\n\nexport function once(fn: () => Handler): () => Handler {\n let result: R;\n let resultP: Promise;\n return function* () {\n if (result) return result;\n if (!(yield* isAsync())) return (result = yield* fn());\n if (resultP) return yield* waitFor(resultP);\n\n let resolve: (result: R) => void, reject: (error: unknown) => void;\n resultP = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n try {\n result = yield* fn();\n // Avoid keeping the promise around\n // now that we have the result.\n resultP = null;\n resolve(result);\n return result;\n } catch (error) {\n reject(error);\n throw error;\n }\n };\n}\n"],"mappings":";;;;;;;AAEA;;AAEO,SAASA,IAAT,CAAiBC,EAAjB,EAAyD;EAC9D,IAAIC,MAAJ;EACA,IAAIC,OAAJ;EACA,OAAO,aAAa;IAClB,IAAID,MAAJ,EAAY,OAAOA,MAAP;IACZ,IAAI,EAAE,OAAO,IAAAE,cAAA,GAAT,CAAJ,EAAyB,OAAQF,MAAM,GAAG,OAAOD,EAAE,EAA1B;IACzB,IAAIE,OAAJ,EAAa,OAAO,OAAO,IAAAE,cAAA,EAAQF,OAAR,CAAd;IAEb,IAAIG,OAAJ,EAAkCC,MAAlC;IACAJ,OAAO,GAAG,IAAIK,OAAJ,CAAY,CAACC,GAAD,EAAMC,GAAN,KAAc;MAClCJ,OAAO,GAAGG,GAAV;MACAF,MAAM,GAAGG,GAAT;IACD,CAHS,CAAV;;IAKA,IAAI;MACFR,MAAM,GAAG,OAAOD,EAAE,EAAlB;MAGAE,OAAO,GAAG,IAAV;MACAG,OAAO,CAACJ,MAAD,CAAP;MACA,OAAOA,MAAP;IACD,CAPD,CAOE,OAAOS,KAAP,EAAc;MACdJ,MAAM,CAACI,KAAD,CAAN;MACA,MAAMA,KAAN;IACD;EACF,CAtBD;AAuBD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/index.js b/node_modules/@babel/core/lib/index.js new file mode 100644 index 0000000..aba93bf --- /dev/null +++ b/node_modules/@babel/core/lib/index.js @@ -0,0 +1,270 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.DEFAULT_EXTENSIONS = void 0; +Object.defineProperty(exports, "File", { + enumerable: true, + get: function () { + return _file.default; + } +}); +exports.OptionManager = void 0; +exports.Plugin = Plugin; +Object.defineProperty(exports, "buildExternalHelpers", { + enumerable: true, + get: function () { + return _buildExternalHelpers.default; + } +}); +Object.defineProperty(exports, "createConfigItem", { + enumerable: true, + get: function () { + return _config.createConfigItem; + } +}); +Object.defineProperty(exports, "createConfigItemAsync", { + enumerable: true, + get: function () { + return _config.createConfigItemAsync; + } +}); +Object.defineProperty(exports, "createConfigItemSync", { + enumerable: true, + get: function () { + return _config.createConfigItemSync; + } +}); +Object.defineProperty(exports, "getEnv", { + enumerable: true, + get: function () { + return _environment.getEnv; + } +}); +Object.defineProperty(exports, "loadOptions", { + enumerable: true, + get: function () { + return _config.loadOptions; + } +}); +Object.defineProperty(exports, "loadOptionsAsync", { + enumerable: true, + get: function () { + return _config.loadOptionsAsync; + } +}); +Object.defineProperty(exports, "loadOptionsSync", { + enumerable: true, + get: function () { + return _config.loadOptionsSync; + } +}); +Object.defineProperty(exports, "loadPartialConfig", { + enumerable: true, + get: function () { + return _config.loadPartialConfig; + } +}); +Object.defineProperty(exports, "loadPartialConfigAsync", { + enumerable: true, + get: function () { + return _config.loadPartialConfigAsync; + } +}); +Object.defineProperty(exports, "loadPartialConfigSync", { + enumerable: true, + get: function () { + return _config.loadPartialConfigSync; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function () { + return _parse.parse; + } +}); +Object.defineProperty(exports, "parseAsync", { + enumerable: true, + get: function () { + return _parse.parseAsync; + } +}); +Object.defineProperty(exports, "parseSync", { + enumerable: true, + get: function () { + return _parse.parseSync; + } +}); +Object.defineProperty(exports, "resolvePlugin", { + enumerable: true, + get: function () { + return _files.resolvePlugin; + } +}); +Object.defineProperty(exports, "resolvePreset", { + enumerable: true, + get: function () { + return _files.resolvePreset; + } +}); +Object.defineProperty((0, exports), "template", { + enumerable: true, + get: function () { + return _template().default; + } +}); +Object.defineProperty((0, exports), "tokTypes", { + enumerable: true, + get: function () { + return _parser().tokTypes; + } +}); +Object.defineProperty(exports, "transform", { + enumerable: true, + get: function () { + return _transform.transform; + } +}); +Object.defineProperty(exports, "transformAsync", { + enumerable: true, + get: function () { + return _transform.transformAsync; + } +}); +Object.defineProperty(exports, "transformFile", { + enumerable: true, + get: function () { + return _transformFile.transformFile; + } +}); +Object.defineProperty(exports, "transformFileAsync", { + enumerable: true, + get: function () { + return _transformFile.transformFileAsync; + } +}); +Object.defineProperty(exports, "transformFileSync", { + enumerable: true, + get: function () { + return _transformFile.transformFileSync; + } +}); +Object.defineProperty(exports, "transformFromAst", { + enumerable: true, + get: function () { + return _transformAst.transformFromAst; + } +}); +Object.defineProperty(exports, "transformFromAstAsync", { + enumerable: true, + get: function () { + return _transformAst.transformFromAstAsync; + } +}); +Object.defineProperty(exports, "transformFromAstSync", { + enumerable: true, + get: function () { + return _transformAst.transformFromAstSync; + } +}); +Object.defineProperty(exports, "transformSync", { + enumerable: true, + get: function () { + return _transform.transformSync; + } +}); +Object.defineProperty((0, exports), "traverse", { + enumerable: true, + get: function () { + return _traverse().default; + } +}); +exports.version = exports.types = void 0; + +var _file = require("./transformation/file/file"); + +var _buildExternalHelpers = require("./tools/build-external-helpers"); + +var _files = require("./config/files"); + +var _environment = require("./config/helpers/environment"); + +function _types() { + const data = require("@babel/types"); + + _types = function () { + return data; + }; + + return data; +} + +Object.defineProperty((0, exports), "types", { + enumerable: true, + get: function () { + return _types(); + } +}); + +function _parser() { + const data = require("@babel/parser"); + + _parser = function () { + return data; + }; + + return data; +} + +function _traverse() { + const data = require("@babel/traverse"); + + _traverse = function () { + return data; + }; + + return data; +} + +function _template() { + const data = require("@babel/template"); + + _template = function () { + return data; + }; + + return data; +} + +var _config = require("./config"); + +var _transform = require("./transform"); + +var _transformFile = require("./transform-file"); + +var _transformAst = require("./transform-ast"); + +var _parse = require("./parse"); + +const version = "7.19.6"; +exports.version = version; +const DEFAULT_EXTENSIONS = Object.freeze([".js", ".jsx", ".es6", ".es", ".mjs", ".cjs"]); +exports.DEFAULT_EXTENSIONS = DEFAULT_EXTENSIONS; + +class OptionManager { + init(opts) { + return (0, _config.loadOptionsSync)(opts); + } + +} + +exports.OptionManager = OptionManager; + +function Plugin(alias) { + throw new Error(`The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`); +} + +0 && (exports.types = exports.traverse = exports.tokTypes = exports.template = 0); + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/core/lib/index.js.map b/node_modules/@babel/core/lib/index.js.map new file mode 100644 index 0000000..bde43bb --- /dev/null +++ b/node_modules/@babel/core/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["version","DEFAULT_EXTENSIONS","Object","freeze","OptionManager","init","opts","loadOptionsSync","Plugin","alias","Error"],"sources":["../src/index.ts"],"sourcesContent":["declare const PACKAGE_JSON: { name: string; version: string };\nexport const version = PACKAGE_JSON.version;\n\nexport { default as File } from \"./transformation/file/file\";\nexport type { default as PluginPass } from \"./transformation/plugin-pass\";\nexport { default as buildExternalHelpers } from \"./tools/build-external-helpers\";\nexport { resolvePlugin, resolvePreset } from \"./config/files\";\n\nexport { getEnv } from \"./config/helpers/environment\";\n\n// NOTE: Lazy re-exports aren't detected by the Node.js CJS-ESM interop.\n// These are handled by pluginInjectNodeReexportsHints in our babel.config.js\n// so that they can work well.\nexport * as types from \"@babel/types\";\nexport { tokTypes } from \"@babel/parser\";\nexport { default as traverse } from \"@babel/traverse\";\nexport { default as template } from \"@babel/template\";\n\nexport {\n createConfigItem,\n createConfigItemSync,\n createConfigItemAsync,\n} from \"./config\";\n\nexport {\n loadPartialConfig,\n loadPartialConfigSync,\n loadPartialConfigAsync,\n loadOptions,\n loadOptionsSync,\n loadOptionsAsync,\n} from \"./config\";\n\nexport type {\n CallerMetadata,\n InputOptions,\n PluginAPI,\n PluginObject,\n PresetAPI,\n PresetObject,\n} from \"./config\";\n\nexport {\n transform,\n transformSync,\n transformAsync,\n type FileResult,\n} from \"./transform\";\nexport {\n transformFile,\n transformFileSync,\n transformFileAsync,\n} from \"./transform-file\";\nexport {\n transformFromAst,\n transformFromAstSync,\n transformFromAstAsync,\n} from \"./transform-ast\";\nexport { parse, parseSync, parseAsync } from \"./parse\";\n\n/**\n * Recommended set of compilable extensions. Not used in @babel/core directly, but meant as\n * as an easy source for tooling making use of @babel/core.\n */\nexport const DEFAULT_EXTENSIONS = Object.freeze([\n \".js\",\n \".jsx\",\n \".es6\",\n \".es\",\n \".mjs\",\n \".cjs\",\n] as const);\n\n// For easier backward-compatibility, provide an API like the one we exposed in Babel 6.\nimport { loadOptionsSync } from \"./config\";\nexport class OptionManager {\n init(opts: {}) {\n return loadOptionsSync(opts);\n }\n}\n\nexport function Plugin(alias: string) {\n throw new Error(\n `The (${alias}) Babel 5 plugin is being run with an unsupported Babel version.`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA;;AAEA;;AACA;;AAEA;;;;;;;;;;;;;;;;;;;AAMA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;;AAwBA;;AAMA;;AAKA;;AAKA;;AAzDO,MAAMA,OAAO,WAAb;;AA+DA,MAAMC,kBAAkB,GAAGC,MAAM,CAACC,MAAP,CAAc,CAC9C,KAD8C,EAE9C,MAF8C,EAG9C,MAH8C,EAI9C,KAJ8C,EAK9C,MAL8C,EAM9C,MAN8C,CAAd,CAA3B;;;AAWA,MAAMC,aAAN,CAAoB;EACzBC,IAAI,CAACC,IAAD,EAAW;IACb,OAAO,IAAAC,uBAAA,EAAgBD,IAAhB,CAAP;EACD;;AAHwB;;;;AAMpB,SAASE,MAAT,CAAgBC,KAAhB,EAA+B;EACpC,MAAM,IAAIC,KAAJ,CACH,QAAOD,KAAM,kEADV,CAAN;AAGD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/parse.js b/node_modules/@babel/core/lib/parse.js new file mode 100644 index 0000000..0c39e6a --- /dev/null +++ b/node_modules/@babel/core/lib/parse.js @@ -0,0 +1,65 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parse = void 0; +exports.parseAsync = parseAsync; +exports.parseSync = parseSync; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _config = require("./config"); + +var _parser = require("./parser"); + +var _normalizeOpts = require("./transformation/normalize-opts"); + +var _rewriteStackTrace = require("./errors/rewrite-stack-trace"); + +const parseRunner = _gensync()(function* parse(code, opts) { + const config = yield* (0, _config.default)(opts); + + if (config === null) { + return null; + } + + return yield* (0, _parser.default)(config.passes, (0, _normalizeOpts.default)(config), code); +}); + +const parse = function parse(code, opts, callback) { + if (typeof opts === "function") { + callback = opts; + opts = undefined; + } + + if (callback === undefined) { + { + return (0, _rewriteStackTrace.beginHiddenCallStack)(parseRunner.sync)(code, opts); + } + } + + (0, _rewriteStackTrace.beginHiddenCallStack)(parseRunner.errback)(code, opts, callback); +}; + +exports.parse = parse; + +function parseSync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(parseRunner.sync)(...args); +} + +function parseAsync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(parseRunner.async)(...args); +} + +0 && 0; + +//# sourceMappingURL=parse.js.map diff --git a/node_modules/@babel/core/lib/parse.js.map b/node_modules/@babel/core/lib/parse.js.map new file mode 100644 index 0000000..1988c9f --- /dev/null +++ b/node_modules/@babel/core/lib/parse.js.map @@ -0,0 +1 @@ +{"version":3,"names":["parseRunner","gensync","parse","code","opts","config","loadConfig","parser","passes","normalizeOptions","callback","undefined","beginHiddenCallStack","sync","errback","parseSync","args","parseAsync","async"],"sources":["../src/parse.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig from \"./config\";\nimport type { InputOptions } from \"./config\";\nimport parser from \"./parser\";\nimport type { ParseResult } from \"./parser\";\nimport normalizeOptions from \"./transformation/normalize-opts\";\nimport type { ValidatedOptions } from \"./config/validation/options\";\n\nimport { beginHiddenCallStack } from \"./errors/rewrite-stack-trace\";\n\ntype FileParseCallback = {\n (err: Error, ast: null): void;\n (err: null, ast: ParseResult | null): void;\n};\n\ntype Parse = {\n (code: string, callback: FileParseCallback): void;\n (\n code: string,\n opts: InputOptions | undefined | null,\n callback: FileParseCallback,\n ): void;\n (code: string, opts?: InputOptions | null): ParseResult | null;\n};\n\nconst parseRunner = gensync(function* parse(\n code: string,\n opts: InputOptions | undefined | null,\n): Handler {\n const config = yield* loadConfig(opts);\n\n if (config === null) {\n return null;\n }\n\n return yield* parser(config.passes, normalizeOptions(config), code);\n});\n\nexport const parse: Parse = function parse(\n code,\n opts?,\n callback?: FileParseCallback,\n) {\n if (typeof opts === \"function\") {\n callback = opts;\n opts = undefined as ValidatedOptions;\n }\n\n if (callback === undefined) {\n if (process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'parse' function expects a callback. If you need to call it synchronously, please use 'parseSync'.\",\n );\n } else {\n // console.warn(\n // \"Starting from Babel 8.0.0, the 'parse' function will expect a callback. If you need to call it synchronously, please use 'parseSync'.\",\n // );\n return beginHiddenCallStack(parseRunner.sync)(code, opts);\n }\n }\n\n beginHiddenCallStack(parseRunner.errback)(code, opts, callback);\n};\n\nexport function parseSync(...args: Parameters) {\n return beginHiddenCallStack(parseRunner.sync)(...args);\n}\nexport function parseAsync(...args: Parameters) {\n return beginHiddenCallStack(parseRunner.async)(...args);\n}\n"],"mappings":";;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;;AAEA;;AAEA;;AAGA;;AAiBA,MAAMA,WAAW,GAAGC,UAAA,CAAQ,UAAUC,KAAV,CAC1BC,IAD0B,EAE1BC,IAF0B,EAGG;EAC7B,MAAMC,MAAM,GAAG,OAAO,IAAAC,eAAA,EAAWF,IAAX,CAAtB;;EAEA,IAAIC,MAAM,KAAK,IAAf,EAAqB;IACnB,OAAO,IAAP;EACD;;EAED,OAAO,OAAO,IAAAE,eAAA,EAAOF,MAAM,CAACG,MAAd,EAAsB,IAAAC,sBAAA,EAAiBJ,MAAjB,CAAtB,EAAgDF,IAAhD,CAAd;AACD,CAXmB,CAApB;;AAaO,MAAMD,KAAY,GAAG,SAASA,KAAT,CAC1BC,IAD0B,EAE1BC,IAF0B,EAG1BM,QAH0B,EAI1B;EACA,IAAI,OAAON,IAAP,KAAgB,UAApB,EAAgC;IAC9BM,QAAQ,GAAGN,IAAX;IACAA,IAAI,GAAGO,SAAP;EACD;;EAED,IAAID,QAAQ,KAAKC,SAAjB,EAA4B;IAKnB;MAIL,OAAO,IAAAC,uCAAA,EAAqBZ,WAAW,CAACa,IAAjC,EAAuCV,IAAvC,EAA6CC,IAA7C,CAAP;IACD;EACF;;EAED,IAAAQ,uCAAA,EAAqBZ,WAAW,CAACc,OAAjC,EAA0CX,IAA1C,EAAgDC,IAAhD,EAAsDM,QAAtD;AACD,CAxBM;;;;AA0BA,SAASK,SAAT,CAAmB,GAAGC,IAAtB,EAAiE;EACtE,OAAO,IAAAJ,uCAAA,EAAqBZ,WAAW,CAACa,IAAjC,EAAuC,GAAGG,IAA1C,CAAP;AACD;;AACM,SAASC,UAAT,CAAoB,GAAGD,IAAvB,EAAmE;EACxE,OAAO,IAAAJ,uCAAA,EAAqBZ,WAAW,CAACkB,KAAjC,EAAwC,GAAGF,IAA3C,CAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/parser/index.js b/node_modules/@babel/core/lib/parser/index.js new file mode 100644 index 0000000..67d1771 --- /dev/null +++ b/node_modules/@babel/core/lib/parser/index.js @@ -0,0 +1,99 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parser; + +function _parser() { + const data = require("@babel/parser"); + + _parser = function () { + return data; + }; + + return data; +} + +function _codeFrame() { + const data = require("@babel/code-frame"); + + _codeFrame = function () { + return data; + }; + + return data; +} + +var _missingPluginHelper = require("./util/missing-plugin-helper"); + +function* parser(pluginPasses, { + parserOpts, + highlightCode = true, + filename = "unknown" +}, code) { + try { + const results = []; + + for (const plugins of pluginPasses) { + for (const plugin of plugins) { + const { + parserOverride + } = plugin; + + if (parserOverride) { + const ast = parserOverride(code, parserOpts, _parser().parse); + if (ast !== undefined) results.push(ast); + } + } + } + + if (results.length === 0) { + return (0, _parser().parse)(code, parserOpts); + } else if (results.length === 1) { + yield* []; + + if (typeof results[0].then === "function") { + throw new Error(`You appear to be using an async parser plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + + return results[0]; + } + + throw new Error("More than one plugin attempted to override parsing."); + } catch (err) { + if (err.code === "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED") { + err.message += "\nConsider renaming the file to '.mjs', or setting sourceType:module " + "or sourceType:unambiguous in your Babel config for this file."; + } + + const { + loc, + missingPlugin + } = err; + + if (loc) { + const codeFrame = (0, _codeFrame().codeFrameColumns)(code, { + start: { + line: loc.line, + column: loc.column + 1 + } + }, { + highlightCode + }); + + if (missingPlugin) { + err.message = `${filename}: ` + (0, _missingPluginHelper.default)(missingPlugin[0], loc, codeFrame); + } else { + err.message = `${filename}: ${err.message}\n\n` + codeFrame; + } + + err.code = "BABEL_PARSE_ERROR"; + } + + throw err; + } +} + +0 && 0; + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/core/lib/parser/index.js.map b/node_modules/@babel/core/lib/parser/index.js.map new file mode 100644 index 0000000..ea7837d --- /dev/null +++ b/node_modules/@babel/core/lib/parser/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["parser","pluginPasses","parserOpts","highlightCode","filename","code","results","plugins","plugin","parserOverride","ast","parse","undefined","push","length","then","Error","err","message","loc","missingPlugin","codeFrame","codeFrameColumns","start","line","column","generateMissingPluginMessage"],"sources":["../../src/parser/index.ts"],"sourcesContent":["import type { Handler } from \"gensync\";\nimport { parse } from \"@babel/parser\";\nimport { codeFrameColumns } from \"@babel/code-frame\";\nimport generateMissingPluginMessage from \"./util/missing-plugin-helper\";\nimport type { PluginPasses } from \"../config\";\n\nexport type ParseResult = ReturnType;\n\nexport default function* parser(\n pluginPasses: PluginPasses,\n { parserOpts, highlightCode = true, filename = \"unknown\" }: any,\n code: string,\n): Handler {\n try {\n const results = [];\n for (const plugins of pluginPasses) {\n for (const plugin of plugins) {\n const { parserOverride } = plugin;\n if (parserOverride) {\n const ast = parserOverride(code, parserOpts, parse);\n\n if (ast !== undefined) results.push(ast);\n }\n }\n }\n\n if (results.length === 0) {\n return parse(code, parserOpts);\n } else if (results.length === 1) {\n // @ts-expect-error - If we want to allow async parsers\n yield* [];\n if (typeof results[0].then === \"function\") {\n throw new Error(\n `You appear to be using an async parser plugin, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, you may need to upgrade ` +\n `your @babel/core version.`,\n );\n }\n return results[0];\n }\n // TODO: Add an error code\n throw new Error(\"More than one plugin attempted to override parsing.\");\n } catch (err) {\n if (err.code === \"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED\") {\n err.message +=\n \"\\nConsider renaming the file to '.mjs', or setting sourceType:module \" +\n \"or sourceType:unambiguous in your Babel config for this file.\";\n // err.code will be changed to BABEL_PARSE_ERROR later.\n }\n\n const { loc, missingPlugin } = err;\n if (loc) {\n const codeFrame = codeFrameColumns(\n code,\n {\n start: {\n line: loc.line,\n column: loc.column + 1,\n },\n },\n {\n highlightCode,\n },\n );\n if (missingPlugin) {\n err.message =\n `${filename}: ` +\n generateMissingPluginMessage(missingPlugin[0], loc, codeFrame);\n } else {\n err.message = `${filename}: ${err.message}\\n\\n` + codeFrame;\n }\n err.code = \"BABEL_PARSE_ERROR\";\n }\n throw err;\n }\n}\n"],"mappings":";;;;;;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;;AAKe,UAAUA,MAAV,CACbC,YADa,EAEb;EAAEC,UAAF;E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GAAG,CAACK,IADL;UAELC,MAAM,EAAEN,GAAG,CAACM,MAAJ,GAAa;QAFhB;MADT,CAFgB,EAQhB;QACEtB;MADF,CARgB,CAAlB;;MAYA,IAAIiB,aAAJ,EAAmB;QACjBH,GAAG,CAACC,OAAJ,GACG,GAAEd,QAAS,IAAZ,GACA,IAAAsB,4BAAA,EAA6BN,aAAa,CAAC,CAAD,CAA1C,EAA+CD,GAA/C,EAAoDE,SAApD,CAFF;MAGD,CAJD,MAIO;QACLJ,GAAG,CAACC,OAAJ,GAAe,GAAEd,QAAS,KAAIa,GAAG,CAACC,OAAQ,MAA5B,GAAoCG,SAAlD;MACD;;MACDJ,GAAG,CAACZ,IAAJ,GAAW,mBAAX;IACD;;IACD,MAAMY,GAAN;EACD;AACF"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js b/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js new file mode 100644 index 0000000..2351b08 --- /dev/null +++ b/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js @@ -0,0 +1,327 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = generateMissingPluginMessage; +const pluginNameMap = { + asyncDoExpressions: { + syntax: { + name: "@babel/plugin-syntax-async-do-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-do-expressions" + } + }, + decimal: { + syntax: { + name: "@babel/plugin-syntax-decimal", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decimal" + } + }, + decorators: { + syntax: { + name: "@babel/plugin-syntax-decorators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decorators" + }, + transform: { + name: "@babel/plugin-proposal-decorators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-decorators" + } + }, + doExpressions: { + syntax: { + name: "@babel/plugin-syntax-do-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-do-expressions" + }, + transform: { + name: "@babel/plugin-proposal-do-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-do-expressions" + } + }, + exportDefaultFrom: { + syntax: { + name: "@babel/plugin-syntax-export-default-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-default-from" + }, + transform: { + name: "@babel/plugin-proposal-export-default-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-export-default-from" + } + }, + flow: { + syntax: { + name: "@babel/plugin-syntax-flow", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-flow" + }, + transform: { + name: "@babel/preset-flow", + url: "https://github.com/babel/babel/tree/main/packages/babel-preset-flow" + } + }, + functionBind: { + syntax: { + name: "@babel/plugin-syntax-function-bind", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-bind" + }, + transform: { + name: "@babel/plugin-proposal-function-bind", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-bind" + } + }, + functionSent: { + syntax: { + name: "@babel/plugin-syntax-function-sent", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-sent" + }, + transform: { + name: "@babel/plugin-proposal-function-sent", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-sent" + } + }, + jsx: { + syntax: { + name: "@babel/plugin-syntax-jsx", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx" + }, + transform: { + name: "@babel/preset-react", + url: "https://github.com/babel/babel/tree/main/packages/babel-preset-react" + } + }, + importAssertions: { + syntax: { + name: "@babel/plugin-syntax-import-assertions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-assertions" + } + }, + pipelineOperator: { + syntax: { + name: "@babel/plugin-syntax-pipeline-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-pipeline-operator" + }, + transform: { + name: "@babel/plugin-proposal-pipeline-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-pipeline-operator" + } + }, + recordAndTuple: { + syntax: { + name: "@babel/plugin-syntax-record-and-tuple", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-record-and-tuple" + } + }, + regexpUnicodeSets: { + syntax: { + name: "@babel/plugin-syntax-unicode-sets-regex", + url: "https://github.com/babel/babel/blob/main/packages/babel-plugin-syntax-unicode-sets-regex/README.md" + }, + transform: { + name: "@babel/plugin-proposal-unicode-sets-regex", + url: "https://github.com/babel/babel/blob/main/packages/babel-plugin-proposalunicode-sets-regex/README.md" + } + }, + throwExpressions: { + syntax: { + name: "@babel/plugin-syntax-throw-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-throw-expressions" + }, + transform: { + name: "@babel/plugin-proposal-throw-expressions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-throw-expressions" + } + }, + typescript: { + syntax: { + name: "@babel/plugin-syntax-typescript", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-typescript" + }, + transform: { + name: "@babel/preset-typescript", + url: "https://github.com/babel/babel/tree/main/packages/babel-preset-typescript" + } + }, + asyncGenerators: { + syntax: { + name: "@babel/plugin-syntax-async-generators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-generators" + }, + transform: { + name: "@babel/plugin-proposal-async-generator-functions", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-async-generator-functions" + } + }, + classProperties: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties" + }, + transform: { + name: "@babel/plugin-proposal-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-class-properties" + } + }, + classPrivateProperties: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties" + }, + transform: { + name: "@babel/plugin-proposal-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-class-properties" + } + }, + classPrivateMethods: { + syntax: { + name: "@babel/plugin-syntax-class-properties", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties" + }, + transform: { + name: "@babel/plugin-proposal-private-methods", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-private-methods" + } + }, + classStaticBlock: { + syntax: { + name: "@babel/plugin-syntax-class-static-block", + url: "https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-syntax-class-static-block" + }, + transform: { + name: "@babel/plugin-proposal-class-static-block", + url: "https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-proposal-class-static-block" + } + }, + dynamicImport: { + syntax: { + name: "@babel/plugin-syntax-dynamic-import", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-dynamic-import" + } + }, + exportNamespaceFrom: { + syntax: { + name: "@babel/plugin-syntax-export-namespace-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-namespace-from" + }, + transform: { + name: "@babel/plugin-proposal-export-namespace-from", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-export-namespace-from" + } + }, + importMeta: { + syntax: { + name: "@babel/plugin-syntax-import-meta", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-meta" + } + }, + logicalAssignment: { + syntax: { + name: "@babel/plugin-syntax-logical-assignment-operators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-logical-assignment-operators" + }, + transform: { + name: "@babel/plugin-proposal-logical-assignment-operators", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-logical-assignment-operators" + } + }, + moduleStringNames: { + syntax: { + name: "@babel/plugin-syntax-module-string-names", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-module-string-names" + } + }, + numericSeparator: { + syntax: { + name: "@babel/plugin-syntax-numeric-separator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-numeric-separator" + }, + transform: { + name: "@babel/plugin-proposal-numeric-separator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-numeric-separator" + } + }, + nullishCoalescingOperator: { + syntax: { + name: "@babel/plugin-syntax-nullish-coalescing-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-nullish-coalescing-operator" + }, + transform: { + name: "@babel/plugin-proposal-nullish-coalescing-operator", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-nullish-coalescing-opearator" + } + }, + objectRestSpread: { + syntax: { + name: "@babel/plugin-syntax-object-rest-spread", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-object-rest-spread" + }, + transform: { + name: "@babel/plugin-proposal-object-rest-spread", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-object-rest-spread" + } + }, + optionalCatchBinding: { + syntax: { + name: "@babel/plugin-syntax-optional-catch-binding", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-catch-binding" + }, + transform: { + name: "@babel/plugin-proposal-optional-catch-binding", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-optional-catch-binding" + } + }, + optionalChaining: { + syntax: { + name: "@babel/plugin-syntax-optional-chaining", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-chaining" + }, + transform: { + name: "@babel/plugin-proposal-optional-chaining", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-optional-chaining" + } + }, + privateIn: { + syntax: { + name: "@babel/plugin-syntax-private-property-in-object", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-private-property-in-object" + }, + transform: { + name: "@babel/plugin-proposal-private-property-in-object", + url: "https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-private-property-in-object" + } + } +}; +pluginNameMap.privateIn.syntax = pluginNameMap.privateIn.transform; + +const getNameURLCombination = ({ + name, + url +}) => `${name} (${url})`; + +function generateMissingPluginMessage(missingPluginName, loc, codeFrame) { + let helpMessage = `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` + `(${loc.line}:${loc.column + 1}):\n\n` + codeFrame; + const pluginInfo = pluginNameMap[missingPluginName]; + + if (pluginInfo) { + const { + syntax: syntaxPlugin, + transform: transformPlugin + } = pluginInfo; + + if (syntaxPlugin) { + const syntaxPluginInfo = getNameURLCombination(syntaxPlugin); + + if (transformPlugin) { + const transformPluginInfo = getNameURLCombination(transformPlugin); + const sectionType = transformPlugin.name.startsWith("@babel/plugin") ? "plugins" : "presets"; + helpMessage += `\n\nAdd ${transformPluginInfo} to the '${sectionType}' section of your Babel config to enable transformation. +If you want to leave it as-is, add ${syntaxPluginInfo} to the 'plugins' section to enable parsing.`; + } else { + helpMessage += `\n\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` + `to enable parsing.`; + } + } + } + + return helpMessage; +} + +0 && 0; + +//# sourceMappingURL=missing-plugin-helper.js.map diff --git a/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js.map b/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js.map new file mode 100644 index 0000000..546a7af --- /dev/null +++ b/node_modules/@babel/core/lib/parser/util/missing-plugin-helper.js.map @@ -0,0 +1 @@ +{"version":3,"names":["pluginNameMap","asyncDoExpressions","syntax","name","url","decimal","decorators","transform","doExpressions","exportDefaultFrom","flow","functionBind","functionSent","jsx","importAssertions","pipelineOperator","recordAndTuple","regexpUnicodeSets","throwExpressions","typescript","asyncGenerators","classProperties","classPrivateProperties","classPrivateMethods","classStaticBlock","dynamicImport","exportNamespaceFrom","importMeta","logicalAssignment","moduleStringNames","numericSeparator","nullishCoalescingOperator","objectRestSpread","optionalCatchBinding","optionalChaining","privateIn","getNameURLCombination","generateMissingPluginMessage","missingPluginName","loc","codeFrame","helpMessage","line","column","pluginInfo","syntaxPlugin","transformPlugin","syntaxPluginInfo","transformPluginInfo","sectionType","startsWith"],"sources":["../../../src/parser/util/missing-plugin-helper.ts"],"sourcesContent":["const pluginNameMap: Record<\n string,\n Partial>>\n> = {\n asyncDoExpressions: {\n syntax: {\n name: \"@babel/plugin-syntax-async-do-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-do-expressions\",\n },\n },\n decimal: {\n syntax: {\n name: \"@babel/plugin-syntax-decimal\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decimal\",\n },\n },\n decorators: {\n syntax: {\n name: \"@babel/plugin-syntax-decorators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-decorators\",\n },\n transform: {\n name: \"@babel/plugin-proposal-decorators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-decorators\",\n },\n },\n doExpressions: {\n syntax: {\n name: \"@babel/plugin-syntax-do-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-do-expressions\",\n },\n transform: {\n name: \"@babel/plugin-proposal-do-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-do-expressions\",\n },\n },\n exportDefaultFrom: {\n syntax: {\n name: \"@babel/plugin-syntax-export-default-from\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-default-from\",\n },\n transform: {\n name: \"@babel/plugin-proposal-export-default-from\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-export-default-from\",\n },\n },\n flow: {\n syntax: {\n name: \"@babel/plugin-syntax-flow\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-flow\",\n },\n transform: {\n name: \"@babel/preset-flow\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-preset-flow\",\n },\n },\n functionBind: {\n syntax: {\n name: \"@babel/plugin-syntax-function-bind\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-bind\",\n },\n transform: {\n name: \"@babel/plugin-proposal-function-bind\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-bind\",\n },\n },\n functionSent: {\n syntax: {\n name: \"@babel/plugin-syntax-function-sent\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-function-sent\",\n },\n transform: {\n name: \"@babel/plugin-proposal-function-sent\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-function-sent\",\n },\n },\n jsx: {\n syntax: {\n name: \"@babel/plugin-syntax-jsx\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-jsx\",\n },\n transform: {\n name: \"@babel/preset-react\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-preset-react\",\n },\n },\n importAssertions: {\n syntax: {\n name: \"@babel/plugin-syntax-import-assertions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-assertions\",\n },\n },\n pipelineOperator: {\n syntax: {\n name: \"@babel/plugin-syntax-pipeline-operator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-pipeline-operator\",\n },\n transform: {\n name: \"@babel/plugin-proposal-pipeline-operator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-pipeline-operator\",\n },\n },\n recordAndTuple: {\n syntax: {\n name: \"@babel/plugin-syntax-record-and-tuple\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-record-and-tuple\",\n },\n },\n regexpUnicodeSets: {\n syntax: {\n name: \"@babel/plugin-syntax-unicode-sets-regex\",\n url: \"https://github.com/babel/babel/blob/main/packages/babel-plugin-syntax-unicode-sets-regex/README.md\",\n },\n transform: {\n name: \"@babel/plugin-proposal-unicode-sets-regex\",\n url: \"https://github.com/babel/babel/blob/main/packages/babel-plugin-proposalunicode-sets-regex/README.md\",\n },\n },\n throwExpressions: {\n syntax: {\n name: \"@babel/plugin-syntax-throw-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-throw-expressions\",\n },\n transform: {\n name: \"@babel/plugin-proposal-throw-expressions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-throw-expressions\",\n },\n },\n typescript: {\n syntax: {\n name: \"@babel/plugin-syntax-typescript\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-typescript\",\n },\n transform: {\n name: \"@babel/preset-typescript\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-preset-typescript\",\n },\n },\n\n // TODO: This plugins are now supported by default by @babel/parser: they can\n // be removed from this list. Although removing them isn't a breaking change,\n // it's better to keep a nice error message for users using older versions of\n // the parser. They can be removed in Babel 8.\n asyncGenerators: {\n syntax: {\n name: \"@babel/plugin-syntax-async-generators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-async-generators\",\n },\n transform: {\n name: \"@babel/plugin-proposal-async-generator-functions\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-async-generator-functions\",\n },\n },\n classProperties: {\n syntax: {\n name: \"@babel/plugin-syntax-class-properties\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties\",\n },\n transform: {\n name: \"@babel/plugin-proposal-class-properties\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-class-properties\",\n },\n },\n classPrivateProperties: {\n syntax: {\n name: \"@babel/plugin-syntax-class-properties\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties\",\n },\n transform: {\n name: \"@babel/plugin-proposal-class-properties\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-class-properties\",\n },\n },\n classPrivateMethods: {\n syntax: {\n name: \"@babel/plugin-syntax-class-properties\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-class-properties\",\n },\n transform: {\n name: \"@babel/plugin-proposal-private-methods\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-private-methods\",\n },\n },\n classStaticBlock: {\n syntax: {\n name: \"@babel/plugin-syntax-class-static-block\",\n url: \"https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-syntax-class-static-block\",\n },\n transform: {\n name: \"@babel/plugin-proposal-class-static-block\",\n url: \"https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-proposal-class-static-block\",\n },\n },\n dynamicImport: {\n syntax: {\n name: \"@babel/plugin-syntax-dynamic-import\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-dynamic-import\",\n },\n },\n exportNamespaceFrom: {\n syntax: {\n name: \"@babel/plugin-syntax-export-namespace-from\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-export-namespace-from\",\n },\n transform: {\n name: \"@babel/plugin-proposal-export-namespace-from\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-export-namespace-from\",\n },\n },\n importMeta: {\n syntax: {\n name: \"@babel/plugin-syntax-import-meta\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-import-meta\",\n },\n },\n logicalAssignment: {\n syntax: {\n name: \"@babel/plugin-syntax-logical-assignment-operators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-logical-assignment-operators\",\n },\n transform: {\n name: \"@babel/plugin-proposal-logical-assignment-operators\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-logical-assignment-operators\",\n },\n },\n moduleStringNames: {\n syntax: {\n name: \"@babel/plugin-syntax-module-string-names\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-module-string-names\",\n },\n },\n numericSeparator: {\n syntax: {\n name: \"@babel/plugin-syntax-numeric-separator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-numeric-separator\",\n },\n transform: {\n name: \"@babel/plugin-proposal-numeric-separator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-numeric-separator\",\n },\n },\n nullishCoalescingOperator: {\n syntax: {\n name: \"@babel/plugin-syntax-nullish-coalescing-operator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-nullish-coalescing-operator\",\n },\n transform: {\n name: \"@babel/plugin-proposal-nullish-coalescing-operator\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-transform-nullish-coalescing-opearator\",\n },\n },\n objectRestSpread: {\n syntax: {\n name: \"@babel/plugin-syntax-object-rest-spread\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-object-rest-spread\",\n },\n transform: {\n name: \"@babel/plugin-proposal-object-rest-spread\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-object-rest-spread\",\n },\n },\n optionalCatchBinding: {\n syntax: {\n name: \"@babel/plugin-syntax-optional-catch-binding\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-catch-binding\",\n },\n transform: {\n name: \"@babel/plugin-proposal-optional-catch-binding\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-optional-catch-binding\",\n },\n },\n optionalChaining: {\n syntax: {\n name: \"@babel/plugin-syntax-optional-chaining\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-optional-chaining\",\n },\n transform: {\n name: \"@babel/plugin-proposal-optional-chaining\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-optional-chaining\",\n },\n },\n privateIn: {\n syntax: {\n name: \"@babel/plugin-syntax-private-property-in-object\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-syntax-private-property-in-object\",\n },\n transform: {\n name: \"@babel/plugin-proposal-private-property-in-object\",\n url: \"https://github.com/babel/babel/tree/main/packages/babel-plugin-proposal-private-property-in-object\",\n },\n },\n};\n\n//todo: we don't have plugin-syntax-private-property-in-object\npluginNameMap.privateIn.syntax = pluginNameMap.privateIn.transform;\n\nconst getNameURLCombination = ({ name, url }: { name: string; url: string }) =>\n `${name} (${url})`;\n\n/*\nReturns a string of the format:\nSupport for the experimental syntax [@babel/parser plugin name] isn't currently enabled ([loc]):\n\n[code frame]\n\nAdd [npm package name] ([url]) to the 'plugins' section of your Babel config\nto enable [parsing|transformation].\n*/\nexport default function generateMissingPluginMessage(\n missingPluginName: string,\n loc: {\n line: number;\n column: number;\n },\n codeFrame: string,\n): string {\n let helpMessage =\n `Support for the experimental syntax '${missingPluginName}' isn't currently enabled ` +\n `(${loc.line}:${loc.column + 1}):\\n\\n` +\n codeFrame;\n const pluginInfo = pluginNameMap[missingPluginName];\n if (pluginInfo) {\n const { syntax: syntaxPlugin, transform: transformPlugin } = pluginInfo;\n if (syntaxPlugin) {\n const syntaxPluginInfo = getNameURLCombination(syntaxPlugin);\n if (transformPlugin) {\n const transformPluginInfo = getNameURLCombination(transformPlugin);\n const sectionType = transformPlugin.name.startsWith(\"@babel/plugin\")\n ? \"plugins\"\n : \"presets\";\n helpMessage += `\\n\\nAdd ${transformPluginInfo} to the '${sectionType}' section of your Babel config to enable transformation.\nIf you want to leave it as-is, add ${syntaxPluginInfo} to the 'plugins' section to enable parsing.`;\n } else {\n helpMessage +=\n `\\n\\nAdd ${syntaxPluginInfo} to the 'plugins' section of your Babel config ` +\n `to enable parsing.`;\n }\n }\n }\n return helpMessage;\n}\n"],"mappings":";;;;;;AAAA,MAAMA,aAGL,GAAG;EACFC,kBAAkB,EAAE;IAClBC,MAAM,EAAE;MACNC,IAAI,EAAE,2CADA;MAENC,GAAG,EAAE;IAFC;EADU,CADlB;EAOFC,OAAO,EAAE;IACPH,MAAM,EAAE;MACNC,IAAI,EAAE,8BADA;MAENC,GAAG,EAAE;IAFC;EADD,CAPP;EAaFE,UAAU,EAAE;IACVJ,MAAM,EAAE;MACNC,IAAI,EAAE,iCADA;MAENC,GAAG,EAAE;IAFC,CADE;IAKVG,SAAS,EAAE;MACTJ,IAAI,EAAE,mCADG;MAETC,GAAG,EAAE;IAFI;EALD,CAbV;EAuBFI,aAAa,EAAE;IACbN,MAAM,EAAE;MACNC,IAAI,EAAE,qCADA;MAENC,GAAG,EAAE;IAFC,CADK;IAKbG,SAAS,EAAE;MACTJ,IAAI,EAAE,uCADG;MAETC,GAAG,EAAE;IAFI;EALE,CAvBb;EAiCFK,iBAAiB,EAAE;IACjBP,MAAM,EAAE;MACNC,IAAI,EAAE,0CADA;MAENC,GAAG,EAAE;IAFC,CADS;IAKjBG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B;MAChB,MAAME,gBAAgB,GAAGX,qBAAqB,CAACS,YAAD,CAA9C;;MACA,IAAIC,eAAJ,EAAqB;QACnB,MAAME,mBAAmB,GAAGZ,qBAAqB,CAACU,eAAD,CAAjD;QACA,MAAMG,WAAW,GAAGH,eAAe,CAAC3C,IAAhB,CAAqB+C,UAArB,CAAgC,eAAhC,IAChB,SADgB,GAEhB,SAFJ;QAGAT,WAAW,IAAK,WAAUO,mBAAoB,YAAWC,WAAY;AAC7E,qCAAqCF,gBAAiB,8CAD9C;MAED,CAPD,MAOO;QACLN,WAAW,IACR,WAAUM,gBAAiB,iDAA5B,GACC,oBAFH;MAGD;IACF;EACF;;EACD,OAAON,WAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/tools/build-external-helpers.js b/node_modules/@babel/core/lib/tools/build-external-helpers.js new file mode 100644 index 0000000..0fa09dc --- /dev/null +++ b/node_modules/@babel/core/lib/tools/build-external-helpers.js @@ -0,0 +1,168 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; + +function helpers() { + const data = require("@babel/helpers"); + + helpers = function () { + return data; + }; + + return data; +} + +function _generator() { + const data = require("@babel/generator"); + + _generator = function () { + return data; + }; + + return data; +} + +function _template() { + const data = require("@babel/template"); + + _template = function () { + return data; + }; + + return data; +} + +function _t() { + const data = require("@babel/types"); + + _t = function () { + return data; + }; + + return data; +} + +var _file = require("../transformation/file/file"); + +const { + arrayExpression, + assignmentExpression, + binaryExpression, + blockStatement, + callExpression, + cloneNode, + conditionalExpression, + exportNamedDeclaration, + exportSpecifier, + expressionStatement, + functionExpression, + identifier, + memberExpression, + objectExpression, + program, + stringLiteral, + unaryExpression, + variableDeclaration, + variableDeclarator +} = _t(); + +const buildUmdWrapper = replacements => _template().default.statement` + (function (root, factory) { + if (typeof define === "function" && define.amd) { + define(AMD_ARGUMENTS, factory); + } else if (typeof exports === "object") { + factory(COMMON_ARGUMENTS); + } else { + factory(BROWSER_ARGUMENTS); + } + })(UMD_ROOT, function (FACTORY_PARAMETERS) { + FACTORY_BODY + }); + `(replacements); + +function buildGlobal(allowlist) { + const namespace = identifier("babelHelpers"); + const body = []; + const container = functionExpression(null, [identifier("global")], blockStatement(body)); + const tree = program([expressionStatement(callExpression(container, [conditionalExpression(binaryExpression("===", unaryExpression("typeof", identifier("global")), stringLiteral("undefined")), identifier("self"), identifier("global"))]))]); + body.push(variableDeclaration("var", [variableDeclarator(namespace, assignmentExpression("=", memberExpression(identifier("global"), namespace), objectExpression([])))])); + buildHelpers(body, namespace, allowlist); + return tree; +} + +function buildModule(allowlist) { + const body = []; + const refs = buildHelpers(body, null, allowlist); + body.unshift(exportNamedDeclaration(null, Object.keys(refs).map(name => { + return exportSpecifier(cloneNode(refs[name]), identifier(name)); + }))); + return program(body, [], "module"); +} + +function buildUmd(allowlist) { + const namespace = identifier("babelHelpers"); + const body = []; + body.push(variableDeclaration("var", [variableDeclarator(namespace, identifier("global"))])); + buildHelpers(body, namespace, allowlist); + return program([buildUmdWrapper({ + FACTORY_PARAMETERS: identifier("global"), + BROWSER_ARGUMENTS: assignmentExpression("=", memberExpression(identifier("root"), namespace), objectExpression([])), + COMMON_ARGUMENTS: identifier("exports"), + AMD_ARGUMENTS: arrayExpression([stringLiteral("exports")]), + FACTORY_BODY: body, + UMD_ROOT: identifier("this") + })]); +} + +function buildVar(allowlist) { + const namespace = identifier("babelHelpers"); + const body = []; + body.push(variableDeclaration("var", [variableDeclarator(namespace, objectExpression([]))])); + const tree = program(body); + buildHelpers(body, namespace, allowlist); + body.push(expressionStatement(namespace)); + return tree; +} + +function buildHelpers(body, namespace, allowlist) { + const getHelperReference = name => { + return namespace ? memberExpression(namespace, identifier(name)) : identifier(`_${name}`); + }; + + const refs = {}; + helpers().list.forEach(function (name) { + if (allowlist && allowlist.indexOf(name) < 0) return; + const ref = refs[name] = getHelperReference(name); + helpers().ensure(name, _file.default); + const { + nodes + } = helpers().get(name, getHelperReference, ref); + body.push(...nodes); + }); + return refs; +} + +function _default(allowlist, outputType = "global") { + let tree; + const build = { + global: buildGlobal, + module: buildModule, + umd: buildUmd, + var: buildVar + }[outputType]; + + if (build) { + tree = build(allowlist); + } else { + throw new Error(`Unsupported output type ${outputType}`); + } + + return (0, _generator().default)(tree).code; +} + +0 && 0; + +//# sourceMappingURL=build-external-helpers.js.map diff --git a/node_modules/@babel/core/lib/tools/build-external-helpers.js.map b/node_modules/@babel/core/lib/tools/build-external-helpers.js.map new file mode 100644 index 0000000..1e18764 --- /dev/null +++ b/node_modules/@babel/core/lib/tools/build-external-helpers.js.map @@ -0,0 +1 @@ +{"version":3,"names":["arrayExpression","assignmentExpression","binaryExpression","blockStatement","callExpression","cloneNode","conditionalExpression","exportNamedDeclaration","exportSpecifier","expressionStatement","functionExpression","identifier","memberExpression","objectExpression","program","stringLiteral","unaryExpression","variableDeclaration","variableDeclarator","buildUmdWrapper","replacements","template","statement","buildGlobal","allowlist","namespace","body","container","tree","push","buildHelpers","buildModule","refs","unshift","Object","keys","map","name","buildUmd","FACTORY_PARAMETERS","BROWSER_ARGUMENTS","COMMON_ARGUMENTS","AMD_ARGUMENTS","FACTORY_BODY","UMD_ROOT","buildVar","getHelperReference","helpers","list","forEach","indexOf","ref","ensure","File","nodes","get","outputType","build","global","module","umd","var","Error","generator","code"],"sources":["../../src/tools/build-external-helpers.ts"],"sourcesContent":["import * as helpers from \"@babel/helpers\";\nimport generator from \"@babel/generator\";\nimport template from \"@babel/template\";\nimport {\n arrayExpression,\n assignmentExpression,\n binaryExpression,\n blockStatement,\n callExpression,\n cloneNode,\n conditionalExpression,\n exportNamedDeclaration,\n exportSpecifier,\n expressionStatement,\n functionExpression,\n identifier,\n memberExpression,\n objectExpression,\n program,\n stringLiteral,\n unaryExpression,\n variableDeclaration,\n variableDeclarator,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport File from \"../transformation/file/file\";\nimport type { PublicReplacements } from \"@babel/template/src/options\";\n\n// Wrapped to avoid wasting time parsing this when almost no-one uses\n// build-external-helpers.\nconst buildUmdWrapper = (replacements: PublicReplacements) =>\n template.statement`\n (function (root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(AMD_ARGUMENTS, factory);\n } else if (typeof exports === \"object\") {\n factory(COMMON_ARGUMENTS);\n } else {\n factory(BROWSER_ARGUMENTS);\n }\n })(UMD_ROOT, function (FACTORY_PARAMETERS) {\n FACTORY_BODY\n });\n `(replacements);\n\nfunction buildGlobal(allowlist?: Array) {\n const namespace = identifier(\"babelHelpers\");\n\n const body: t.Statement[] = [];\n const container = functionExpression(\n null,\n [identifier(\"global\")],\n blockStatement(body),\n );\n const tree = program([\n expressionStatement(\n callExpression(container, [\n // typeof global === \"undefined\" ? self : global\n conditionalExpression(\n binaryExpression(\n \"===\",\n unaryExpression(\"typeof\", identifier(\"global\")),\n stringLiteral(\"undefined\"),\n ),\n identifier(\"self\"),\n identifier(\"global\"),\n ),\n ]),\n ),\n ]);\n\n body.push(\n variableDeclaration(\"var\", [\n variableDeclarator(\n namespace,\n assignmentExpression(\n \"=\",\n memberExpression(identifier(\"global\"), namespace),\n objectExpression([]),\n ),\n ),\n ]),\n );\n\n buildHelpers(body, namespace, allowlist);\n\n return tree;\n}\n\nfunction buildModule(allowlist?: Array) {\n const body: t.Statement[] = [];\n const refs = buildHelpers(body, null, allowlist);\n\n body.unshift(\n exportNamedDeclaration(\n null,\n Object.keys(refs).map(name => {\n return exportSpecifier(cloneNode(refs[name]), identifier(name));\n }),\n ),\n );\n\n return program(body, [], \"module\");\n}\n\nfunction buildUmd(allowlist?: Array) {\n const namespace = identifier(\"babelHelpers\");\n\n const body: t.Statement[] = [];\n body.push(\n variableDeclaration(\"var\", [\n variableDeclarator(namespace, identifier(\"global\")),\n ]),\n );\n\n buildHelpers(body, namespace, allowlist);\n\n return program([\n buildUmdWrapper({\n FACTORY_PARAMETERS: identifier(\"global\"),\n BROWSER_ARGUMENTS: assignmentExpression(\n \"=\",\n memberExpression(identifier(\"root\"), namespace),\n objectExpression([]),\n ),\n COMMON_ARGUMENTS: identifier(\"exports\"),\n AMD_ARGUMENTS: arrayExpression([stringLiteral(\"exports\")]),\n FACTORY_BODY: body,\n UMD_ROOT: identifier(\"this\"),\n }),\n ]);\n}\n\nfunction buildVar(allowlist?: Array) {\n const namespace = identifier(\"babelHelpers\");\n\n const body: t.Statement[] = [];\n body.push(\n variableDeclaration(\"var\", [\n variableDeclarator(namespace, objectExpression([])),\n ]),\n );\n const tree = program(body);\n buildHelpers(body, namespace, allowlist);\n body.push(expressionStatement(namespace));\n return tree;\n}\n\nfunction buildHelpers(\n body: t.Statement[],\n namespace: t.Expression,\n allowlist?: Array,\n): Record;\nfunction buildHelpers(\n body: t.Statement[],\n namespace: null,\n allowlist?: Array,\n): Record;\n\nfunction buildHelpers(\n body: t.Statement[],\n namespace: t.Expression | null,\n allowlist?: Array,\n) {\n const getHelperReference = (name: string) => {\n return namespace\n ? memberExpression(namespace, identifier(name))\n : identifier(`_${name}`);\n };\n\n const refs: { [key: string]: t.Identifier | t.MemberExpression } = {};\n helpers.list.forEach(function (name) {\n if (allowlist && allowlist.indexOf(name) < 0) return;\n\n const ref = (refs[name] = getHelperReference(name));\n\n helpers.ensure(name, File);\n const { nodes } = helpers.get(name, getHelperReference, ref);\n\n body.push(...nodes);\n });\n return refs;\n}\nexport default function (\n allowlist?: Array,\n outputType: \"global\" | \"module\" | \"umd\" | \"var\" = \"global\",\n) {\n let tree: t.Program;\n\n const build = {\n global: buildGlobal,\n module: buildModule,\n umd: buildUmd,\n var: buildVar,\n }[outputType];\n\n if (build) {\n tree = build(allowlist);\n } else {\n throw new Error(`Unsupported output type ${outputType}`);\n }\n\n return generator(tree).code;\n}\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;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AAtC,CAAlB;IAEAzB,IAAI,CAACG,IAAL,CAAU,GAAGyB,KAAb;EACD,CATD;EAUA,OAAOtB,IAAP;AACD;;AACc,kBACbR,SADa,EAEbgC,UAA+C,GAAG,QAFrC,EAGb;EACA,IAAI5B,IAAJ;EAEA,MAAM6B,KAAK,GAAG;IACZC,MAAM,EAAEnC,WADI;IAEZoC,MAAM,EAAE5B,WAFI;IAGZ6B,GAAG,EAAEtB,QAHO;IAIZuB,GAAG,EAAEhB;EAJO,EAKZW,UALY,CAAd;;EAOA,IAAIC,KAAJ,EAAW;IACT7B,IAAI,GAAG6B,KAAK,CAACjC,SAAD,CAAZ;EACD,CAFD,MAEO;IACL,MAAM,IAAIsC,KAAJ,CAAW,2BAA0BN,UAAW,EAAhD,CAAN;EACD;;EAED,OAAO,IAAAO,oBAAA,EAAUnC,IAAV,EAAgBoC,IAAvB;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform-ast.js b/node_modules/@babel/core/lib/transform-ast.js new file mode 100644 index 0000000..3b8e147 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-ast.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformFromAst = void 0; +exports.transformFromAstAsync = transformFromAstAsync; +exports.transformFromAstSync = transformFromAstSync; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _config = require("./config"); + +var _transformation = require("./transformation"); + +var _rewriteStackTrace = require("./errors/rewrite-stack-trace"); + +const transformFromAstRunner = _gensync()(function* (ast, code, opts) { + const config = yield* (0, _config.default)(opts); + if (config === null) return null; + if (!ast) throw new Error("No AST given"); + return yield* (0, _transformation.run)(config, code, ast); +}); + +const transformFromAst = function transformFromAst(ast, code, optsOrCallback, maybeCallback) { + let opts; + let callback; + + if (typeof optsOrCallback === "function") { + callback = optsOrCallback; + opts = undefined; + } else { + opts = optsOrCallback; + callback = maybeCallback; + } + + if (callback === undefined) { + { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformFromAstRunner.sync)(ast, code, opts); + } + } + + (0, _rewriteStackTrace.beginHiddenCallStack)(transformFromAstRunner.errback)(ast, code, opts, callback); +}; + +exports.transformFromAst = transformFromAst; + +function transformFromAstSync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformFromAstRunner.sync)(...args); +} + +function transformFromAstAsync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformFromAstRunner.async)(...args); +} + +0 && 0; + +//# sourceMappingURL=transform-ast.js.map diff --git a/node_modules/@babel/core/lib/transform-ast.js.map b/node_modules/@babel/core/lib/transform-ast.js.map new file mode 100644 index 0000000..e60b5f2 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-ast.js.map @@ -0,0 +1 @@ +{"version":3,"names":["transformFromAstRunner","gensync","ast","code","opts","config","loadConfig","Error","run","transformFromAst","optsOrCallback","maybeCallback","callback","undefined","beginHiddenCallStack","sync","errback","transformFromAstSync","args","transformFromAstAsync","async"],"sources":["../src/transform-ast.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig from \"./config\";\nimport type { InputOptions, ResolvedConfig } from \"./config\";\nimport { run } from \"./transformation\";\nimport type * as t from \"@babel/types\";\n\nimport { beginHiddenCallStack } from \"./errors/rewrite-stack-trace\";\n\nimport type { FileResult, FileResultCallback } from \"./transformation\";\ntype AstRoot = t.File | t.Program;\n\ntype TransformFromAst = {\n (ast: AstRoot, code: string, callback: FileResultCallback): void;\n (\n ast: AstRoot,\n code: string,\n opts: InputOptions | undefined | null,\n callback: FileResultCallback,\n ): void;\n (ast: AstRoot, code: string, opts?: InputOptions | null): FileResult | null;\n};\n\nconst transformFromAstRunner = gensync(function* (\n ast: AstRoot,\n code: string,\n opts: InputOptions | undefined | null,\n): Handler {\n const config: ResolvedConfig | null = yield* loadConfig(opts);\n if (config === null) return null;\n\n if (!ast) throw new Error(\"No AST given\");\n\n return yield* run(config, code, ast);\n});\n\nexport const transformFromAst: TransformFromAst = function transformFromAst(\n ast,\n code,\n optsOrCallback?: InputOptions | null | undefined | FileResultCallback,\n maybeCallback?: FileResultCallback,\n) {\n let opts: InputOptions | undefined | null;\n let callback: FileResultCallback | undefined;\n if (typeof optsOrCallback === \"function\") {\n callback = optsOrCallback;\n opts = undefined;\n } else {\n opts = optsOrCallback;\n callback = maybeCallback;\n }\n\n if (callback === undefined) {\n if (process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'transformFromAst' function expects a callback. If you need to call it synchronously, please use 'transformFromAstSync'.\",\n );\n } else {\n // console.warn(\n // \"Starting from Babel 8.0.0, the 'transformFromAst' function will expect a callback. If you need to call it synchronously, please use 'transformFromAstSync'.\",\n // );\n return beginHiddenCallStack(transformFromAstRunner.sync)(ast, code, opts);\n }\n }\n\n beginHiddenCallStack(transformFromAstRunner.errback)(\n ast,\n code,\n opts,\n callback,\n );\n};\n\nexport function transformFromAstSync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(transformFromAstRunner.sync)(...args);\n}\n\nexport function transformFromAstAsync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(transformFromAstRunner.async)(...args);\n}\n"],"mappings":";;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;;AAEA;;AAGA;;AAgBA,MAAMA,sBAAsB,GAAGC,UAAA,CAAQ,WACrCC,GADqC,EAErCC,IAFqC,EAGrCC,IAHqC,EAIT;EAC5B,MAAMC,MAA6B,GAAG,OAAO,IAAAC,eAAA,EAAWF,IAAX,CAA7C;EACA,IAAIC,MAAM,KAAK,IAAf,EAAqB,OAAO,IAAP;EAErB,IAAI,CAACH,GAAL,EAAU,MAAM,IAAIK,KAAJ,CAAU,cAAV,CAAN;EAEV,OAAO,OAAO,IAAAC,mBAAA,EAAIH,MAAJ,EAAYF,IAAZ,EAAkBD,GAAlB,CAAd;AACD,CAX8B,CAA/B;;AAaO,MAAMO,gBAAkC,GAAG,SAASA,gBAAT,CAChDP,GADgD,EAEhDC,IAFgD,EAGhDO,cAHgD,EAIhDC,aAJgD,EAKhD;EACA,IAAIP,IAAJ;EACA,IAAIQ,QAAJ;;EACA,IAAI,OAAOF,cAAP,KAA0B,UAA9B,EAA0C;IACxCE,QAAQ,GAAGF,cAAX;IACAN,IAAI,GAAGS,SAAP;EACD,CAHD,MAGO;IACLT,IAAI,GAAGM,cAAP;IACAE,QAAQ,GAAGD,aAAX;EACD;;EAED,IAAIC,QAAQ,KAAKC,SAAjB,EAA4B;IAKnB;MAIL,OAAO,IAAAC,uCAAA,EAAqBd,sBAAsB,CAACe,IAA5C,EAAkDb,GAAlD,EAAuDC,IAAvD,EAA6DC,IAA7D,CAAP;IACD;EACF;;EAED,IAAAU,uCAAA,EAAqBd,sBAAsB,CAACgB,OAA5C,EACEd,GADF,EAEEC,IAFF,EAGEC,IAHF,EAIEQ,QAJF;AAMD,CAnCM;;;;AAqCA,SAASK,oBAAT,CACL,GAAGC,IADE,EAEL;EACA,OAAO,IAAAJ,uCAAA,EAAqBd,sBAAsB,CAACe,IAA5C,EAAkD,GAAGG,IAArD,CAAP;AACD;;AAEM,SAASC,qBAAT,CACL,GAAGD,IADE,EAEL;EACA,OAAO,IAAAJ,uCAAA,EAAqBd,sBAAsB,CAACoB,KAA5C,EAAmD,GAAGF,IAAtD,CAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform-file-browser.js b/node_modules/@babel/core/lib/transform-file-browser.js new file mode 100644 index 0000000..97ad366 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-file-browser.js @@ -0,0 +1,30 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformFile = void 0; +exports.transformFileAsync = transformFileAsync; +exports.transformFileSync = transformFileSync; + +const transformFile = function transformFile(filename, opts, callback) { + if (typeof opts === "function") { + callback = opts; + } + + callback(new Error("Transforming files is not supported in browsers"), null); +}; + +exports.transformFile = transformFile; + +function transformFileSync() { + throw new Error("Transforming files is not supported in browsers"); +} + +function transformFileAsync() { + return Promise.reject(new Error("Transforming files is not supported in browsers")); +} + +0 && 0; + +//# sourceMappingURL=transform-file-browser.js.map diff --git a/node_modules/@babel/core/lib/transform-file-browser.js.map b/node_modules/@babel/core/lib/transform-file-browser.js.map new file mode 100644 index 0000000..8bc230f --- /dev/null +++ b/node_modules/@babel/core/lib/transform-file-browser.js.map @@ -0,0 +1 @@ +{"version":3,"names":["transformFile","filename","opts","callback","Error","transformFileSync","transformFileAsync","Promise","reject"],"sources":["../src/transform-file-browser.ts"],"sourcesContent":["// duplicated from transform-file so we do not have to import anything here\ntype TransformFile = {\n (filename: string, callback: (error: Error, file: null) => void): void;\n (\n filename: string,\n opts: any,\n callback: (error: Error, file: null) => void,\n ): void;\n};\n\nexport const transformFile: TransformFile = function transformFile(\n filename,\n opts,\n callback?: (error: Error, file: null) => void,\n) {\n if (typeof opts === \"function\") {\n callback = opts;\n }\n\n callback(new Error(\"Transforming files is not supported in browsers\"), null);\n};\n\nexport function transformFileSync(): never {\n throw new Error(\"Transforming files is not supported in browsers\");\n}\n\nexport function transformFileAsync() {\n return Promise.reject(\n new Error(\"Transforming files is not supported in browsers\"),\n );\n}\n"],"mappings":";;;;;;;;;AAUO,MAAMA,aAA4B,GAAG,SAASA,aAAT,CAC1CC,QAD0C,EAE1CC,IAF0C,EAG1CC,QAH0C,EAI1C;EACA,IAAI,OAAOD,IAAP,KAAgB,UAApB,EAAgC;IAC9BC,QAAQ,GAAGD,IAAX;EACD;;EAEDC,QAAQ,CAAC,IAAIC,KAAJ,CAAU,iDAAV,CAAD,EAA+D,IAA/D,CAAR;AACD,CAVM;;;;AAYA,SAASC,iBAAT,GAAoC;EACzC,MAAM,IAAID,KAAJ,CAAU,iDAAV,CAAN;AACD;;AAEM,SAASE,kBAAT,GAA8B;EACnC,OAAOC,OAAO,CAACC,MAAR,CACL,IAAIJ,KAAJ,CAAU,iDAAV,CADK,CAAP;AAGD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform-file.js b/node_modules/@babel/core/lib/transform-file.js new file mode 100644 index 0000000..7edcc05 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-file.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transformFile = transformFile; +exports.transformFileAsync = transformFileAsync; +exports.transformFileSync = transformFileSync; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _config = require("./config"); + +var _transformation = require("./transformation"); + +var fs = require("./gensync-utils/fs"); + +({}); + +const transformFileRunner = _gensync()(function* (filename, opts) { + const options = Object.assign({}, opts, { + filename + }); + const config = yield* (0, _config.default)(options); + if (config === null) return null; + const code = yield* fs.readFile(filename, "utf8"); + return yield* (0, _transformation.run)(config, code); +}); + +function transformFile(...args) { + return transformFileRunner.errback(...args); +} + +function transformFileSync(...args) { + return transformFileRunner.sync(...args); +} + +function transformFileAsync(...args) { + return transformFileRunner.async(...args); +} + +0 && 0; + +//# sourceMappingURL=transform-file.js.map diff --git a/node_modules/@babel/core/lib/transform-file.js.map b/node_modules/@babel/core/lib/transform-file.js.map new file mode 100644 index 0000000..d770cb0 --- /dev/null +++ b/node_modules/@babel/core/lib/transform-file.js.map @@ -0,0 +1 @@ +{"version":3,"names":["transformFileRunner","gensync","filename","opts","options","config","loadConfig","code","fs","readFile","run","transformFile","args","errback","transformFileSync","sync","transformFileAsync","async"],"sources":["../src/transform-file.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig from \"./config\";\nimport type { InputOptions, ResolvedConfig } from \"./config\";\nimport { run } from \"./transformation\";\nimport type { FileResult, FileResultCallback } from \"./transformation\";\nimport * as fs from \"./gensync-utils/fs\";\n\ntype transformFileBrowserType = typeof import(\"./transform-file-browser\");\ntype transformFileType = typeof import(\"./transform-file\");\n\n// Kind of gross, but essentially asserting that the exports of this module are the same as the\n// exports of transform-file-browser, since this file may be replaced at bundle time with\n// transform-file-browser.\n({} as any as transformFileBrowserType as transformFileType);\n\nconst transformFileRunner = gensync(function* (\n filename: string,\n opts?: InputOptions,\n): Handler {\n const options = { ...opts, filename };\n\n const config: ResolvedConfig | null = yield* loadConfig(options);\n if (config === null) return null;\n\n const code = yield* fs.readFile(filename, \"utf8\");\n return yield* run(config, code);\n});\n\n// @ts-expect-error TS doesn't detect that this signature is compatible\nexport function transformFile(\n filename: string,\n callback: FileResultCallback,\n): void;\nexport function transformFile(\n filename: string,\n opts: InputOptions | undefined | null,\n callback: FileResultCallback,\n): void;\nexport function transformFile(\n ...args: Parameters\n) {\n return transformFileRunner.errback(...args);\n}\n\nexport function transformFileSync(\n ...args: Parameters\n) {\n return transformFileRunner.sync(...args);\n}\nexport function transformFileAsync(\n ...args: Parameters\n) {\n return transformFileRunner.async(...args);\n}\n"],"mappings":";;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;;AAEA;;AAEA;;AAQA,CAAC,EAAD;;AAEA,MAAMA,mBAAmB,GAAGC,UAAA,CAAQ,WAClCC,QADkC,EAElCC,IAFkC,EAGN;EAC5B,MAAMC,OAAO,qBAAQD,IAAR;IAAcD;EAAd,EAAb;EAEA,MAAMG,MAA6B,GAAG,OAAO,IAAAC,eAAA,EAAWF,OAAX,CAA7C;EACA,IAAIC,MAAM,KAAK,IAAf,EAAqB,OAAO,IAAP;EAErB,MAAME,IAAI,GAAG,OAAOC,EAAE,CAACC,QAAH,CAAYP,QAAZ,EAAsB,MAAtB,CAApB;EACA,OAAO,OAAO,IAAAQ,mBAAA,EAAIL,MAAJ,EAAYE,IAAZ,CAAd;AACD,CAX2B,CAA5B;;AAuBO,SAASI,aAAT,CACL,GAAGC,IADE,EAEL;EACA,OAAOZ,mBAAmB,CAACa,OAApB,CAA4B,GAAGD,IAA/B,CAAP;AACD;;AAEM,SAASE,iBAAT,CACL,GAAGF,IADE,EAEL;EACA,OAAOZ,mBAAmB,CAACe,IAApB,CAAyB,GAAGH,IAA5B,CAAP;AACD;;AACM,SAASI,kBAAT,CACL,GAAGJ,IADE,EAEL;EACA,OAAOZ,mBAAmB,CAACiB,KAApB,CAA0B,GAAGL,IAA7B,CAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transform.js b/node_modules/@babel/core/lib/transform.js new file mode 100644 index 0000000..3a5af74 --- /dev/null +++ b/node_modules/@babel/core/lib/transform.js @@ -0,0 +1,65 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.transform = void 0; +exports.transformAsync = transformAsync; +exports.transformSync = transformSync; + +function _gensync() { + const data = require("gensync"); + + _gensync = function () { + return data; + }; + + return data; +} + +var _config = require("./config"); + +var _transformation = require("./transformation"); + +var _rewriteStackTrace = require("./errors/rewrite-stack-trace"); + +const transformRunner = _gensync()(function* transform(code, opts) { + const config = yield* (0, _config.default)(opts); + if (config === null) return null; + return yield* (0, _transformation.run)(config, code); +}); + +const transform = function transform(code, optsOrCallback, maybeCallback) { + let opts; + let callback; + + if (typeof optsOrCallback === "function") { + callback = optsOrCallback; + opts = undefined; + } else { + opts = optsOrCallback; + callback = maybeCallback; + } + + if (callback === undefined) { + { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformRunner.sync)(code, opts); + } + } + + (0, _rewriteStackTrace.beginHiddenCallStack)(transformRunner.errback)(code, opts, callback); +}; + +exports.transform = transform; + +function transformSync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformRunner.sync)(...args); +} + +function transformAsync(...args) { + return (0, _rewriteStackTrace.beginHiddenCallStack)(transformRunner.async)(...args); +} + +0 && 0; + +//# sourceMappingURL=transform.js.map diff --git a/node_modules/@babel/core/lib/transform.js.map b/node_modules/@babel/core/lib/transform.js.map new file mode 100644 index 0000000..2f18c9f --- /dev/null +++ b/node_modules/@babel/core/lib/transform.js.map @@ -0,0 +1 @@ +{"version":3,"names":["transformRunner","gensync","transform","code","opts","config","loadConfig","run","optsOrCallback","maybeCallback","callback","undefined","beginHiddenCallStack","sync","errback","transformSync","args","transformAsync","async"],"sources":["../src/transform.ts"],"sourcesContent":["import gensync, { type Handler } from \"gensync\";\n\nimport loadConfig from \"./config\";\nimport type { InputOptions, ResolvedConfig } from \"./config\";\nimport { run } from \"./transformation\";\n\nimport type { FileResult, FileResultCallback } from \"./transformation\";\nimport { beginHiddenCallStack } from \"./errors/rewrite-stack-trace\";\n\nexport type { FileResult } from \"./transformation\";\n\ntype Transform = {\n (code: string, callback: FileResultCallback): void;\n (\n code: string,\n opts: InputOptions | undefined | null,\n callback: FileResultCallback,\n ): void;\n (code: string, opts?: InputOptions | null): FileResult | null;\n};\n\nconst transformRunner = gensync(function* transform(\n code: string,\n opts?: InputOptions,\n): Handler {\n const config: ResolvedConfig | null = yield* loadConfig(opts);\n if (config === null) return null;\n\n return yield* run(config, code);\n});\n\nexport const transform: Transform = function transform(\n code,\n optsOrCallback?: InputOptions | null | undefined | FileResultCallback,\n maybeCallback?: FileResultCallback,\n) {\n let opts: InputOptions | undefined | null;\n let callback: FileResultCallback | undefined;\n if (typeof optsOrCallback === \"function\") {\n callback = optsOrCallback;\n opts = undefined;\n } else {\n opts = optsOrCallback;\n callback = maybeCallback;\n }\n\n if (callback === undefined) {\n if (process.env.BABEL_8_BREAKING) {\n throw new Error(\n \"Starting from Babel 8.0.0, the 'transform' function expects a callback. If you need to call it synchronously, please use 'transformSync'.\",\n );\n } else {\n // console.warn(\n // \"Starting from Babel 8.0.0, the 'transform' function will expect a callback. If you need to call it synchronously, please use 'transformSync'.\",\n // );\n return beginHiddenCallStack(transformRunner.sync)(code, opts);\n }\n }\n\n beginHiddenCallStack(transformRunner.errback)(code, opts, callback);\n};\n\nexport function transformSync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(transformRunner.sync)(...args);\n}\nexport function transformAsync(\n ...args: Parameters\n) {\n return beginHiddenCallStack(transformRunner.async)(...args);\n}\n"],"mappings":";;;;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;;AAEA;;AAGA;;AAcA,MAAMA,eAAe,GAAGC,UAAA,CAAQ,UAAUC,SAAV,CAC9BC,IAD8B,EAE9BC,IAF8B,EAGF;EAC5B,MAAMC,MAA6B,GAAG,OAAO,IAAAC,eAAA,EAAWF,IAAX,CAA7C;EACA,IAAIC,MAAM,KAAK,IAAf,EAAqB,OAAO,IAAP;EAErB,OAAO,OAAO,IAAAE,mBAAA,EAAIF,MAAJ,EAAYF,IAAZ,CAAd;AACD,CARuB,CAAxB;;AAUO,MAAMD,SAAoB,GAAG,SAASA,SAAT,CAClCC,IADkC,EAElCK,cAFkC,EAGlCC,aAHkC,EAIlC;EACA,IAAIL,IAAJ;EACA,IAAIM,QAAJ;;EACA,IAAI,OAAOF,cAAP,KAA0B,UAA9B,EAA0C;IACxCE,QAAQ,GAAGF,cAAX;IACAJ,IAAI,GAAGO,SAAP;EACD,CAHD,MAGO;IACLP,IAAI,GAAGI,cAAP;IACAE,QAAQ,GAAGD,aAAX;EACD;;EAED,IAAIC,QAAQ,KAAKC,SAAjB,EAA4B;IAKnB;MAIL,OAAO,IAAAC,uCAAA,EAAqBZ,eAAe,CAACa,IAArC,EAA2CV,IAA3C,EAAiDC,IAAjD,CAAP;IACD;EACF;;EAED,IAAAQ,uCAAA,EAAqBZ,eAAe,CAACc,OAArC,EAA8CX,IAA9C,EAAoDC,IAApD,EAA0DM,QAA1D;AACD,CA7BM;;;;AA+BA,SAASK,aAAT,CACL,GAAGC,IADE,EAEL;EACA,OAAO,IAAAJ,uCAAA,EAAqBZ,eAAe,CAACa,IAArC,EAA2C,GAAGG,IAA9C,CAAP;AACD;;AACM,SAASC,cAAT,CACL,GAAGD,IADE,EAEL;EACA,OAAO,IAAAJ,uCAAA,EAAqBZ,eAAe,CAACkB,KAArC,EAA4C,GAAGF,IAA/C,CAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js b/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js new file mode 100644 index 0000000..65745ed --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js @@ -0,0 +1,97 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = loadBlockHoistPlugin; + +function _traverse() { + const data = require("@babel/traverse"); + + _traverse = function () { + return data; + }; + + return data; +} + +var _plugin = require("../config/plugin"); + +let LOADED_PLUGIN; + +function loadBlockHoistPlugin() { + if (!LOADED_PLUGIN) { + LOADED_PLUGIN = new _plugin.default(Object.assign({}, blockHoistPlugin, { + visitor: _traverse().default.explode(blockHoistPlugin.visitor) + }), {}); + } + + return LOADED_PLUGIN; +} + +function priority(bodyNode) { + const priority = bodyNode == null ? void 0 : bodyNode._blockHoist; + if (priority == null) return 1; + if (priority === true) return 2; + return priority; +} + +function stableSort(body) { + const buckets = Object.create(null); + + for (let i = 0; i < body.length; i++) { + const n = body[i]; + const p = priority(n); + const bucket = buckets[p] || (buckets[p] = []); + bucket.push(n); + } + + const keys = Object.keys(buckets).map(k => +k).sort((a, b) => b - a); + let index = 0; + + for (const key of keys) { + const bucket = buckets[key]; + + for (const n of bucket) { + body[index++] = n; + } + } + + return body; +} + +const blockHoistPlugin = { + name: "internal.blockHoist", + visitor: { + Block: { + exit({ + node + }) { + const { + body + } = node; + let max = Math.pow(2, 30) - 1; + let hasChange = false; + + for (let i = 0; i < body.length; i++) { + const n = body[i]; + const p = priority(n); + + if (p > max) { + hasChange = true; + break; + } + + max = p; + } + + if (!hasChange) return; + node.body = stableSort(body.slice()); + } + + } + } +}; +0 && 0; + +//# sourceMappingURL=block-hoist-plugin.js.map diff --git a/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js.map b/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js.map new file mode 100644 index 0000000..2813227 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/block-hoist-plugin.js.map @@ -0,0 +1 @@ +{"version":3,"names":["LOADED_PLUGIN","loadBlockHoistPlugin","Plugin","blockHoistPlugin","visitor","traverse","explode","priority","bodyNode","_blockHoist","stableSort","body","buckets","Object","create","i","length","n","p","bucket","push","keys","map","k","sort","a","b","index","key","name","Block","exit","node","max","hasChange","slice"],"sources":["../../src/transformation/block-hoist-plugin.ts"],"sourcesContent":["import traverse from \"@babel/traverse\";\nimport type { Statement } from \"@babel/types\";\nimport type { PluginObject } from \"../config\";\nimport Plugin from \"../config/plugin\";\n\nlet LOADED_PLUGIN: Plugin | void;\n\nexport default function loadBlockHoistPlugin(): Plugin {\n if (!LOADED_PLUGIN) {\n // cache the loaded blockHoist plugin plugin\n LOADED_PLUGIN = new Plugin(\n {\n ...blockHoistPlugin,\n visitor: traverse.explode(blockHoistPlugin.visitor),\n },\n {},\n );\n }\n\n return LOADED_PLUGIN;\n}\nfunction priority(bodyNode: Statement & { _blockHoist?: number | true }) {\n const priority = bodyNode?._blockHoist;\n if (priority == null) return 1;\n if (priority === true) return 2;\n return priority;\n}\n\nfunction stableSort(body: Statement[]) {\n // By default, we use priorities of 0-4.\n const buckets = Object.create(null);\n\n // By collecting into buckets, we can guarantee a stable sort.\n for (let i = 0; i < body.length; i++) {\n const n = body[i];\n const p = priority(n);\n\n // In case some plugin is setting an unexpected priority.\n const bucket = buckets[p] || (buckets[p] = []);\n bucket.push(n);\n }\n\n // Sort our keys in descending order. Keys are unique, so we don't have to\n // worry about stability.\n const keys = Object.keys(buckets)\n .map(k => +k)\n .sort((a, b) => b - a);\n\n let index = 0;\n for (const key of keys) {\n const bucket = buckets[key];\n for (const n of bucket) {\n body[index++] = n;\n }\n }\n return body;\n}\n\nconst blockHoistPlugin: PluginObject = {\n /**\n * [Please add a description.]\n *\n * Priority:\n *\n * - 0 We want this to be at the **very** bottom\n * - 1 Default node position\n * - 2 Priority over normal nodes\n * - 3 We want this to be at the **very** top\n * - 4 Reserved for the helpers used to implement module imports.\n */\n\n name: \"internal.blockHoist\",\n\n visitor: {\n Block: {\n exit({ node }) {\n const { body } = node;\n\n // Largest SMI\n let max = 2 ** 30 - 1;\n let hasChange = false;\n for (let i = 0; i < body.length; i++) {\n const n = body[i];\n const p = priority(n);\n if (p > max) {\n hasChange = true;\n break;\n }\n max = p;\n }\n if (!hasChange) return;\n\n // My kingdom for a stable sort!\n node.body = stableSort(body.slice());\n },\n },\n },\n};\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAGA;;AAEA,IAAIA,aAAJ;;AAEe,SAASC,oBAAT,GAAwC;EACrD,IAAI,CAACD,aAAL,EAAoB;IAElBA,aAAa,GAAG,IAAIE,eAAJ,mBAETC,gBAFS;MAGZC,OAAO,EAAEC,mBAAA,CAASC,OAAT,CAAiBH,gBAAgB,CAACC,OAAlC;IAHG,IAKd,EALc,CAAhB;EAOD;;EAED,OAAOJ,aAAP;AACD;;AACD,SAASO,QAAT,CAAkBC,QAAlB,EAAyE;EACvE,MAAMD,QAAQ,GAAGC,QAAH,oBAAGA,QAAQ,CAAEC,WAA3B;EACA,IAAIF,QAAQ,IAAI,IAAhB,EAAsB,OAAO,CAAP;EACtB,IAAIA,QAAQ,KAAK,IAAjB,EAAuB,OAAO,CAAP;EACvB,OAAOA,QAAP;AACD;;AAED,SAASG,UAAT,CAAoBC,IAApB,EAAuC;EAErC,MAAMC,OAAO,GAAGC,MAAM,CAACC,MAAP,CAAc,IAAd,CAAhB;;EAGA,KAAK,IAAIC,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGJ,IAAI,CAACK,MAAzB,EAAiCD,CAAC,EAAlC,EAAsC;IACpC,MAAME,CAAC,GAAGN,IAAI,CAACI,CAAD,CAAd;IACA,MAAMG,CAAC,GAAGX,QAAQ,CAACU,CAAD,CAAlB;IAGA,MAAME,MAAM,GAAGP,OAAO,CAACM,CAAD,CAAP,KAAeN,OAAO,CAACM,CAAD,CAAP,GAAa,EAA5B,CAAf;IACAC,MAAM,CAACC,IAAP,CAAYH,CAAZ;EACD;;EAID,MAAMI,IAAI,GAAGR,MAAM,CAACQ,IAAP,CAAYT,OAAZ,EACVU,GADU,CACNC,CAAC,IAAI,CAACA,CADA,EAEVC,IAFU,CAEL,CAACC,CAAD,EAAIC,CAAJ,KAAUA,CAAC,GAAGD,CAFT,CAAb;EAIA,IAAIE,KAAK,GAAG,CAAZ;;EACA,KAAK,MAAMC,GAAX,IAAkBP,IAAlB,EAAwB;IACtB,MAAMF,MAAM,GAAGP,OAAO,CAACgB,GAAD,CAAtB;;IACA,KAAK,MAAMX,CAAX,IAAgBE,MAAhB,EAAwB;MACtBR,IAAI,CAACgB,KAAK,EAAN,CAAJ,GAAgBV,CAAhB;IACD;EACF;;EACD,OAAON,IAAP;AACD;;AAED,MAAMR,gBAA8B,GAAG;EAarC0B,IAAI,EAAE,qBAb+B;EAerCzB,OAAO,EAAE;IACP0B,KAAK,EAAE;MACLC,IAAI,CAAC;QAAEC;MAAF,CAAD,EAAW;QACb,MAAM;UAAErB;QAAF,IAAWqB,IAAjB;QAGA,IAAIC,GAAG,GAAG,YAAK,EAAL,IAAU,CAApB;QACA,IAAIC,SAAS,GAAG,KAAhB;;QACA,KAAK,IAAInB,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGJ,IAAI,CAACK,MAAzB,EAAiCD,CAAC,EAAlC,EAAsC;UACpC,MAAME,CAAC,GAAGN,IAAI,CAACI,CAAD,CAAd;UACA,MAAMG,CAAC,GAAGX,QAAQ,CAACU,CAAD,CAAlB;;UACA,IAAIC,CAAC,GAAGe,GAAR,EAAa;YACXC,SAAS,GAAG,IAAZ;YACA;UACD;;UACDD,GAAG,GAAGf,CAAN;QACD;;QACD,IAAI,CAACgB,SAAL,EAAgB;QAGhBF,IAAI,CAACrB,IAAL,GAAYD,UAAU,CAACC,IAAI,CAACwB,KAAL,EAAD,CAAtB;MACD;;IApBI;EADA;AAf4B,CAAvC"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/file/file.js b/node_modules/@babel/core/lib/transformation/file/file.js new file mode 100644 index 0000000..d4f3723 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/file.js @@ -0,0 +1,257 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +function helpers() { + const data = require("@babel/helpers"); + + helpers = function () { + return data; + }; + + return data; +} + +function _traverse() { + const data = require("@babel/traverse"); + + _traverse = function () { + return data; + }; + + return data; +} + +function _codeFrame() { + const data = require("@babel/code-frame"); + + _codeFrame = function () { + return data; + }; + + return data; +} + +function _t() { + const data = require("@babel/types"); + + _t = function () { + return data; + }; + + return data; +} + +function _helperModuleTransforms() { + const data = require("@babel/helper-module-transforms"); + + _helperModuleTransforms = function () { + return data; + }; + + return data; +} + +function _semver() { + const data = require("semver"); + + _semver = function () { + return data; + }; + + return data; +} + +const { + cloneNode, + interpreterDirective +} = _t(); + +const errorVisitor = { + enter(path, state) { + const loc = path.node.loc; + + if (loc) { + state.loc = loc; + path.stop(); + } + } + +}; + +class File { + constructor(options, { + code, + ast, + inputMap + }) { + this._map = new Map(); + this.opts = void 0; + this.declarations = {}; + this.path = void 0; + this.ast = void 0; + this.scope = void 0; + this.metadata = {}; + this.code = ""; + this.inputMap = void 0; + this.hub = { + file: this, + getCode: () => this.code, + getScope: () => this.scope, + addHelper: this.addHelper.bind(this), + buildError: this.buildCodeFrameError.bind(this) + }; + this.opts = options; + this.code = code; + this.ast = ast; + this.inputMap = inputMap; + this.path = _traverse().NodePath.get({ + hub: this.hub, + parentPath: null, + parent: this.ast, + container: this.ast, + key: "program" + }).setContext(); + this.scope = this.path.scope; + } + + get shebang() { + const { + interpreter + } = this.path.node; + return interpreter ? interpreter.value : ""; + } + + set shebang(value) { + if (value) { + this.path.get("interpreter").replaceWith(interpreterDirective(value)); + } else { + this.path.get("interpreter").remove(); + } + } + + set(key, val) { + if (key === "helpersNamespace") { + throw new Error("Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." + "If you are using @babel/plugin-external-helpers you will need to use a newer " + "version than the one you currently have installed. " + "If you have your own implementation, you'll want to explore using 'helperGenerator' " + "alongside 'file.availableHelper()'."); + } + + this._map.set(key, val); + } + + get(key) { + return this._map.get(key); + } + + has(key) { + return this._map.has(key); + } + + getModuleName() { + return (0, _helperModuleTransforms().getModuleName)(this.opts, this.opts); + } + + addImport() { + throw new Error("This API has been removed. If you're looking for this " + "functionality in Babel 7, you should import the " + "'@babel/helper-module-imports' module and use the functions exposed " + " from that module, such as 'addNamed' or 'addDefault'."); + } + + availableHelper(name, versionRange) { + let minVersion; + + try { + minVersion = helpers().minVersion(name); + } catch (err) { + if (err.code !== "BABEL_HELPER_UNKNOWN") throw err; + return false; + } + + if (typeof versionRange !== "string") return true; + if (_semver().valid(versionRange)) versionRange = `^${versionRange}`; + return !_semver().intersects(`<${minVersion}`, versionRange) && !_semver().intersects(`>=8.0.0`, versionRange); + } + + addHelper(name) { + const declar = this.declarations[name]; + if (declar) return cloneNode(declar); + const generator = this.get("helperGenerator"); + + if (generator) { + const res = generator(name); + if (res) return res; + } + + helpers().ensure(name, File); + const uid = this.declarations[name] = this.scope.generateUidIdentifier(name); + const dependencies = {}; + + for (const dep of helpers().getDependencies(name)) { + dependencies[dep] = this.addHelper(dep); + } + + const { + nodes, + globals + } = helpers().get(name, dep => dependencies[dep], uid, Object.keys(this.scope.getAllBindings())); + globals.forEach(name => { + if (this.path.scope.hasBinding(name, true)) { + this.path.scope.rename(name); + } + }); + nodes.forEach(node => { + node._compact = true; + }); + this.path.unshiftContainer("body", nodes); + this.path.get("body").forEach(path => { + if (nodes.indexOf(path.node) === -1) return; + if (path.isVariableDeclaration()) this.scope.registerDeclaration(path); + }); + return uid; + } + + addTemplateObject() { + throw new Error("This function has been moved into the template literal transform itself."); + } + + buildCodeFrameError(node, msg, _Error = SyntaxError) { + let loc = node && (node.loc || node._loc); + + if (!loc && node) { + const state = { + loc: null + }; + (0, _traverse().default)(node, errorVisitor, this.scope, state); + loc = state.loc; + let txt = "This is an error on an internal node. Probably an internal error."; + if (loc) txt += " Location has been estimated."; + msg += ` (${txt})`; + } + + if (loc) { + const { + highlightCode = true + } = this.opts; + msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, { + start: { + line: loc.start.line, + column: loc.start.column + 1 + }, + end: loc.end && loc.start.line === loc.end.line ? { + line: loc.end.line, + column: loc.end.column + 1 + } : undefined + }, { + highlightCode + }); + } + + return new _Error(msg); + } + +} + +exports.default = File; +0 && 0; + +//# sourceMappingURL=file.js.map diff --git a/node_modules/@babel/core/lib/transformation/file/file.js.map b/node_modules/@babel/core/lib/transformation/file/file.js.map new file mode 100644 index 0000000..3eb7a45 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/file.js.map @@ -0,0 +1 @@ +{"version":3,"names":["cloneNode","interpreterDirective","errorVisitor","enter","path","state","loc","node","stop","File","constructor","options","code","ast","inputMap","_map","Map","opts","declarations","scope","metadata","hub","file","getCode","getScope","addHelper","bind","buildError","buildCodeFrameError","NodePath","get","parentPath","parent","container","key","setContext","shebang","interpreter","value","replaceWith","remove","set","val","Error","has","getModuleName","addImport","availableHelper","name","versionRange","minVersion","helpers","err","semver","valid","intersects","declar","generator","res","ensure","uid","generateUidIdentifier","dependencies","dep","getDependencies","nodes","globals","Object","keys","getAllBindings","forEach","hasBinding","rename","_compact","unshiftContainer","indexOf","isVariableDeclaration","registerDeclaration","addTemplateObject","msg","_Error","SyntaxError","_loc","traverse","txt","highlightCode","codeFrameColumns","start","line","column","end","undefined"],"sources":["../../../src/transformation/file/file.ts"],"sourcesContent":["import * as helpers from \"@babel/helpers\";\nimport { NodePath } from \"@babel/traverse\";\nimport type { HubInterface, Visitor, Scope } from \"@babel/traverse\";\nimport { codeFrameColumns } from \"@babel/code-frame\";\nimport traverse from \"@babel/traverse\";\nimport { cloneNode, interpreterDirective } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport { getModuleName } from \"@babel/helper-module-transforms\";\nimport semver from \"semver\";\n\nimport type { NormalizedFile } from \"../normalize-file\";\n\nconst errorVisitor: Visitor<{ loc: NodeLocation[\"loc\"] | null }> = {\n enter(path, state) {\n const loc = path.node.loc;\n if (loc) {\n state.loc = loc;\n path.stop();\n }\n },\n};\n\nexport type NodeLocation = {\n loc?: {\n end?: {\n line: number;\n column: number;\n };\n start: {\n line: number;\n column: number;\n };\n };\n _loc?: {\n end?: {\n line: number;\n column: number;\n };\n start: {\n line: number;\n column: number;\n };\n };\n};\n\nexport default class File {\n _map: Map = new Map();\n opts: { [key: string]: any };\n declarations: { [key: string]: t.Identifier } = {};\n path: NodePath;\n ast: t.File;\n scope: Scope;\n metadata: { [key: string]: any } = {};\n code: string = \"\";\n inputMap: any;\n\n hub: HubInterface & { file: File } = {\n // keep it for the usage in babel-core, ex: path.hub.file.opts.filename\n file: this,\n getCode: () => this.code,\n getScope: () => this.scope,\n addHelper: this.addHelper.bind(this),\n buildError: this.buildCodeFrameError.bind(this),\n };\n\n constructor(options: {}, { code, ast, inputMap }: NormalizedFile) {\n this.opts = options;\n this.code = code;\n this.ast = ast;\n this.inputMap = inputMap;\n\n this.path = NodePath.get({\n hub: this.hub,\n parentPath: null,\n parent: this.ast,\n container: this.ast,\n key: \"program\",\n }).setContext() as NodePath;\n this.scope = this.path.scope;\n }\n\n /**\n * Provide backward-compatible access to the interpreter directive handling\n * in Babel 6.x. If you are writing a plugin for Babel 7.x, it would be\n * best to use 'program.interpreter' directly.\n */\n get shebang(): string {\n const { interpreter } = this.path.node;\n return interpreter ? interpreter.value : \"\";\n }\n set shebang(value: string) {\n if (value) {\n this.path.get(\"interpreter\").replaceWith(interpreterDirective(value));\n } else {\n this.path.get(\"interpreter\").remove();\n }\n }\n\n set(key: unknown, val: unknown) {\n if (key === \"helpersNamespace\") {\n throw new Error(\n \"Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility.\" +\n \"If you are using @babel/plugin-external-helpers you will need to use a newer \" +\n \"version than the one you currently have installed. \" +\n \"If you have your own implementation, you'll want to explore using 'helperGenerator' \" +\n \"alongside 'file.availableHelper()'.\",\n );\n }\n\n this._map.set(key, val);\n }\n\n get(key: unknown): any {\n return this._map.get(key);\n }\n\n has(key: unknown): boolean {\n return this._map.has(key);\n }\n\n getModuleName(): string | undefined | null {\n return getModuleName(this.opts, this.opts);\n }\n\n addImport() {\n throw new Error(\n \"This API has been removed. If you're looking for this \" +\n \"functionality in Babel 7, you should import the \" +\n \"'@babel/helper-module-imports' module and use the functions exposed \" +\n \" from that module, such as 'addNamed' or 'addDefault'.\",\n );\n }\n\n /**\n * Check if a given helper is available in @babel/core's helper list.\n *\n * This _also_ allows you to pass a Babel version specifically. If the\n * helper exists, but was not available for the full given range, it will be\n * considered unavailable.\n */\n availableHelper(name: string, versionRange?: string | null): boolean {\n let minVersion;\n try {\n minVersion = helpers.minVersion(name);\n } catch (err) {\n if (err.code !== \"BABEL_HELPER_UNKNOWN\") throw err;\n\n return false;\n }\n\n if (typeof versionRange !== \"string\") return true;\n\n // semver.intersects() has some surprising behavior with comparing ranges\n // with pre-release versions. We add '^' to ensure that we are always\n // comparing ranges with ranges, which sidesteps this logic.\n // For example:\n //\n // semver.intersects(`<7.0.1`, \"7.0.0-beta.0\") // false - surprising\n // semver.intersects(`<7.0.1`, \"^7.0.0-beta.0\") // true - expected\n //\n // This is because the first falls back to\n //\n // semver.satisfies(\"7.0.0-beta.0\", `<7.0.1`) // false - surprising\n //\n // and this fails because a prerelease version can only satisfy a range\n // if it is a prerelease within the same major/minor/patch range.\n //\n // Note: If this is found to have issues, please also revisit the logic in\n // transform-runtime's definitions.js file.\n if (semver.valid(versionRange)) versionRange = `^${versionRange}`;\n\n return (\n !semver.intersects(`<${minVersion}`, versionRange) &&\n !semver.intersects(`>=8.0.0`, versionRange)\n );\n }\n\n addHelper(name: string): t.Identifier {\n const declar = this.declarations[name];\n if (declar) return cloneNode(declar);\n\n const generator = this.get(\"helperGenerator\");\n if (generator) {\n const res = generator(name);\n if (res) return res;\n }\n\n // make sure that the helper exists\n helpers.ensure(name, File);\n\n const uid = (this.declarations[name] =\n this.scope.generateUidIdentifier(name));\n\n const dependencies: { [key: string]: t.Identifier } = {};\n for (const dep of helpers.getDependencies(name)) {\n dependencies[dep] = this.addHelper(dep);\n }\n\n const { nodes, globals } = helpers.get(\n name,\n dep => dependencies[dep],\n uid,\n Object.keys(this.scope.getAllBindings()),\n );\n\n globals.forEach(name => {\n if (this.path.scope.hasBinding(name, true /* noGlobals */)) {\n this.path.scope.rename(name);\n }\n });\n\n nodes.forEach(node => {\n // @ts-expect-error Fixeme: document _compact node property\n node._compact = true;\n });\n\n this.path.unshiftContainer(\"body\", nodes);\n // TODO: NodePath#unshiftContainer should automatically register new\n // bindings.\n this.path.get(\"body\").forEach(path => {\n if (nodes.indexOf(path.node) === -1) return;\n if (path.isVariableDeclaration()) this.scope.registerDeclaration(path);\n });\n\n return uid;\n }\n\n addTemplateObject() {\n throw new Error(\n \"This function has been moved into the template literal transform itself.\",\n );\n }\n\n buildCodeFrameError(\n node: NodeLocation | undefined | null,\n msg: string,\n _Error: typeof Error = SyntaxError,\n ): Error {\n let loc = node && (node.loc || node._loc);\n\n if (!loc && node) {\n const state: { loc?: NodeLocation[\"loc\"] | null } = {\n loc: null,\n };\n traverse(node as t.Node, errorVisitor, this.scope, state);\n loc = state.loc;\n\n let txt =\n \"This is an error on an internal node. Probably an internal error.\";\n if (loc) txt += \" Location has been estimated.\";\n\n msg += ` (${txt})`;\n }\n\n if (loc) {\n const { highlightCode = true } = this.opts;\n\n msg +=\n \"\\n\" +\n codeFrameColumns(\n this.code,\n {\n start: {\n line: loc.start.line,\n column: loc.start.column + 1,\n },\n end:\n loc.end && loc.start.line === loc.end.line\n ? {\n line: loc.end.line,\n column: loc.end.column + 1,\n }\n : undefined,\n },\n { highlightCode },\n );\n }\n\n return new _Error(msg);\n }\n}\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEA;EAAA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,EAGjBC,MAAoB,GAAGC,WAHN,EAIV;IACP,IAAI3E,GAAG,GAAGC,IAAI,KAAKA,IAAI,CAACD,GAAL,IAAYC,IAAI,CAAC2E,IAAtB,CAAd;;IAEA,IAAI,CAAC5E,GAAD,IAAQC,IAAZ,EAAkB;MAChB,MAAMF,KAA2C,GAAG;QAClDC,GAAG,EAAE;MAD6C,CAApD;MAGA,IAAA6E,mBAAA,EAAS5E,IAAT,EAAyBL,YAAzB,EAAuC,KAAKiB,KAA5C,EAAmDd,KAAnD;MACAC,GAAG,GAAGD,KAAK,CAACC,GAAZ;MAEA,IAAI8E,GAAG,GACL,mEADF;MAEA,IAAI9E,GAAJ,EAAS8E,GAAG,IAAI,+BAAP;MAETL,GAAG,IAAK,KAAIK,GAAI,GAAhB;IACD;;IAED,IAAI9E,GAAJ,EAAS;MACP,MAAM;QAAE+E,aAAa,GAAG;MAAlB,IAA2B,KAAKpE,IAAtC;MAEA8D,GAAG,IACD,OACA,IAAAO,6BAAA,EACE,KAAK1E,IADP,EAEE;QACE2E,KAAK,EAAE;UACLC,IAAI,EAAElF,GAAG,CAACiF,KAAJ,CAAUC,IADX;UAELC,MAAM,EAAEnF,GAAG,CAACiF,KAAJ,CAAUE,MAAV,GAAmB;QAFtB,CADT;QAKEC,GAAG,EACDpF,GAAG,CAACoF,GAAJ,IAAWpF,GAAG,CAACiF,KAAJ,CAAUC,IAAV,KAAmBlF,GAAG,CAACoF,GAAJ,CAAQF,IAAtC,GACI;UACEA,IAAI,EAAElF,GAAG,CAACoF,GAAJ,CAAQF,IADhB;UAEEC,MAAM,EAAEnF,GAAG,CAACoF,GAAJ,CAAQD,MAAR,GAAiB;QAF3B,CADJ,GAKIE;MAXR,CAFF,EAeE;QAAEN;MAAF,CAfF,CAFF;IAmBD;;IAED,OAAO,IAAIL,MAAJ,CAAWD,GAAX,CAAP;EACD;;AA1OuB"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/file/generate.js b/node_modules/@babel/core/lib/transformation/file/generate.js new file mode 100644 index 0000000..9b7aae7 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/generate.js @@ -0,0 +1,98 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = generateCode; + +function _convertSourceMap() { + const data = require("convert-source-map"); + + _convertSourceMap = function () { + return data; + }; + + return data; +} + +function _generator() { + const data = require("@babel/generator"); + + _generator = function () { + return data; + }; + + return data; +} + +var _mergeMap = require("./merge-map"); + +function generateCode(pluginPasses, file) { + const { + opts, + ast, + code, + inputMap + } = file; + const { + generatorOpts + } = opts; + const results = []; + + for (const plugins of pluginPasses) { + for (const plugin of plugins) { + const { + generatorOverride + } = plugin; + + if (generatorOverride) { + const result = generatorOverride(ast, generatorOpts, code, _generator().default); + if (result !== undefined) results.push(result); + } + } + } + + let result; + + if (results.length === 0) { + result = (0, _generator().default)(ast, generatorOpts, code); + } else if (results.length === 1) { + result = results[0]; + + if (typeof result.then === "function") { + throw new Error(`You appear to be using an async codegen plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`); + } + } else { + throw new Error("More than one plugin attempted to override codegen."); + } + + let { + code: outputCode, + decodedMap: outputMap = result.map + } = result; + + if (outputMap) { + if (inputMap) { + outputMap = (0, _mergeMap.default)(inputMap.toObject(), outputMap, generatorOpts.sourceFileName); + } else { + outputMap = result.map; + } + } + + if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") { + outputCode += "\n" + _convertSourceMap().fromObject(outputMap).toComment(); + } + + if (opts.sourceMaps === "inline") { + outputMap = null; + } + + return { + outputCode, + outputMap + }; +} + +0 && 0; + +//# sourceMappingURL=generate.js.map diff --git a/node_modules/@babel/core/lib/transformation/file/generate.js.map b/node_modules/@babel/core/lib/transformation/file/generate.js.map new file mode 100644 index 0000000..c477829 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/generate.js.map @@ -0,0 +1 @@ +{"version":3,"names":["generateCode","pluginPasses","file","opts","ast","code","inputMap","generatorOpts","results","plugins","plugin","generatorOverride","result","generate","undefined","push","length","then","Error","outputCode","decodedMap","outputMap","map","mergeSourceMap","toObject","sourceFileName","sourceMaps","convertSourceMap","fromObject","toComment"],"sources":["../../../src/transformation/file/generate.ts"],"sourcesContent":["import type { PluginPasses } from \"../../config\";\nimport convertSourceMap from \"convert-source-map\";\ntype SourceMap = any;\nimport generate from \"@babel/generator\";\n\nimport type File from \"./file\";\nimport mergeSourceMap from \"./merge-map\";\n\nexport default function generateCode(\n pluginPasses: PluginPasses,\n file: File,\n): {\n outputCode: string;\n outputMap: SourceMap | null;\n} {\n const { opts, ast, code, inputMap } = file;\n const { generatorOpts } = opts;\n\n const results = [];\n for (const plugins of pluginPasses) {\n for (const plugin of plugins) {\n const { generatorOverride } = plugin;\n if (generatorOverride) {\n const result = generatorOverride(ast, generatorOpts, code, generate);\n\n if (result !== undefined) results.push(result);\n }\n }\n }\n\n let result;\n if (results.length === 0) {\n result = generate(ast, generatorOpts, code);\n } else if (results.length === 1) {\n result = results[0];\n\n if (typeof result.then === \"function\") {\n throw new Error(\n `You appear to be using an async codegen plugin, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, ` +\n `you may need to upgrade your @babel/core version.`,\n );\n }\n } else {\n throw new Error(\"More than one plugin attempted to override codegen.\");\n }\n\n // Decoded maps are faster to merge, so we attempt to get use the decodedMap\n // first. But to preserve backwards compat with older Generator, we'll fall\n // back to the encoded map.\n let { code: outputCode, decodedMap: outputMap = result.map } = result;\n\n if (outputMap) {\n if (inputMap) {\n // mergeSourceMap returns an encoded map\n outputMap = mergeSourceMap(\n inputMap.toObject(),\n outputMap,\n generatorOpts.sourceFileName,\n );\n } else {\n // We cannot output a decoded map, so retrieve the encoded form. Because\n // the decoded form is free, it's fine to prioritize decoded first.\n outputMap = result.map;\n }\n }\n\n if (opts.sourceMaps === \"inline\" || opts.sourceMaps === \"both\") {\n outputCode += \"\\n\" + convertSourceMap.fromObject(outputMap).to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;;EAKD,IAAI;IAAEb,IAAI,EAAEc,UAAR;IAAoBC,UAAU,EAAEC,SAAS,GAAGT,MAAM,CAACU;EAAnD,IAA2DV,MAA/D;;EAEA,IAAIS,SAAJ,EAAe;IACb,IAAIf,QAAJ,EAAc;MAEZe,SAAS,GAAG,IAAAE,iBAAA,EACVjB,QAAQ,CAACkB,QAAT,EADU,EAEVH,SAFU,EAGVd,aAAa,CAACkB,cAHJ,CAAZ;IAKD,CAPD,MAOO;MAGLJ,SAAS,GAAGT,MAAM,CAACU,GAAnB;IACD;EACF;;EAED,IAAInB,IAAI,CAACuB,UAAL,KAAoB,QAApB,IAAgCvB,IAAI,CAACuB,UAAL,KAAoB,MAAxD,EAAgE;IAC9DP,UAAU,IAAI,OAAOQ,mBAAA,CAAiBC,UAAjB,CAA4BP,SAA5B,EAAuCQ,SAAvC,EAArB;EACD;;EAED,IAAI1B,IAAI,CAACuB,UAAL,KAAoB,QAAxB,EAAkC;IAChCL,SAAS,GAAG,IAAZ;EACD;;EAED,OAAO;IAAEF,UAAF;IAAcE;EAAd,CAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/file/merge-map.js b/node_modules/@babel/core/lib/transformation/file/merge-map.js new file mode 100644 index 0000000..422ec27 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/merge-map.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mergeSourceMap; + +function _remapping() { + const data = require("@ampproject/remapping"); + + _remapping = function () { + return data; + }; + + return data; +} + +function mergeSourceMap(inputMap, map, sourceFileName) { + const source = sourceFileName.replace(/\\/g, "/"); + let found = false; + + const result = _remapping()(rootless(map), (s, ctx) => { + if (s === source && !found) { + found = true; + ctx.source = ""; + return rootless(inputMap); + } + + return null; + }); + + if (typeof inputMap.sourceRoot === "string") { + result.sourceRoot = inputMap.sourceRoot; + } + + return Object.assign({}, result); +} + +function rootless(map) { + return Object.assign({}, map, { + sourceRoot: null + }); +} + +0 && 0; + +//# sourceMappingURL=merge-map.js.map diff --git a/node_modules/@babel/core/lib/transformation/file/merge-map.js.map b/node_modules/@babel/core/lib/transformation/file/merge-map.js.map new file mode 100644 index 0000000..528562c --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/file/merge-map.js.map @@ -0,0 +1 @@ +{"version":3,"names":["mergeSourceMap","inputMap","map","sourceFileName","source","replace","found","result","remapping","rootless","s","ctx","sourceRoot"],"sources":["../../../src/transformation/file/merge-map.ts"],"sourcesContent":["type SourceMap = any;\nimport remapping from \"@ampproject/remapping\";\n\nexport default function mergeSourceMap(\n inputMap: SourceMap,\n map: SourceMap,\n sourceFileName: string,\n): SourceMap {\n // On win32 machines, the sourceFileName uses backslash paths like\n // `C:\\foo\\bar.js`. But sourcemaps are always posix paths, so we need to\n // normalize to regular slashes before we can merge (else we won't find the\n // source associated with our input map).\n // This mirrors code done while generating the output map at\n // https://github.com/babel/babel/blob/5c2fcadc9ae34fd20dd72b1111d5cf50476d700d/packages/babel-generator/src/source-map.ts#L102\n const source = sourceFileName.replace(/\\\\/g, \"/\");\n\n // Prevent an infinite recursion if one of the input map's sources has the\n // same resolved path as the input map. In the case, it would keep find the\n // input map, then get it's sources which will include a path like the input\n // map, on and on.\n let found = false;\n const result = remapping(rootless(map), (s, ctx) => {\n if (s === source && !found) {\n found = true;\n // We empty the source location, which will prevent the sourcemap from\n // becoming relative to the input's location. Eg, if we're transforming a\n // file 'foo/bar.js', and it is a transformation of a `baz.js` file in the\n // same directory, the expected output is just `baz.js`. Without this step,\n // it would become `foo/baz.js`.\n ctx.source = \"\";\n\n return rootless(inputMap);\n }\n\n return null;\n });\n\n if (typeof inputMap.sourceRoot === \"string\") {\n result.sourceRoot = inputMap.sourceRoot;\n }\n\n // remapping returns a SourceMap class type, but this breaks code downstream in\n // @babel/traverse and @babel/types that relies on data being plain objects.\n // When it encounters the sourcemap type it outputs a \"don't know how to turn\n // this value into a node\" error. As a result, we are converting the merged\n // sourcemap to a plain js object.\n return { ...result };\n}\n\nfunction rootless(map: SourceMap): SourceMap {\n return {\n ...map,\n\n // This is a bit hack. Remapping will create absolute sources in our\n // sourcemap, but we want to maintain sources relative to the sourceRoot.\n // We'll re-add the sourceRoot after remapping.\n sourceRoot: null,\n };\n}\n"],"mappings":";;;;;;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAEe,SAASA,cAAT,CACbC,QADa,EAEbC,GAFa,EAGbC,cAHa,EAIF;EAOX,MAAMC,MAAM,GAAGD,cAAc,CAACE,OAAf,CAAuB,KAAvB,EAA8B,GAA9B,CAAf;EAMA,IAAIC,KAAK,GAAG,KAAZ;;EACA,MAAMC,MAAM,GAAGC,YAAA,CAAUC,QAAQ,CAACP,GAAD,CAAlB,EAAyB,CAACQ,CAAD,EAAIC,GAAJ,KAAY;IAClD,IAAID,CAAC,KAAKN,MAAN,IAAgB,CAACE,KAArB,EAA4B;MAC1BA,KAAK,GAAG,IAAR;MAMAK,GAAG,CAACP,MAAJ,GAAa,EAAb;MAEA,OAAOK,QAAQ,CAACR,QAAD,CAAf;IACD;;IAED,OAAO,IAAP;EACD,CAdc,CAAf;;EAgBA,IAAI,OAAOA,QAAQ,CAACW,UAAhB,KAA+B,QAAnC,EAA6C;IAC3CL,MAAM,CAACK,UAAP,GAAoBX,QAAQ,CAACW,UAA7B;EACD;;EAOD,yBAAYL,MAAZ;AACD;;AAED,SAASE,QAAT,CAAkBP,GAAlB,EAA6C;EAC3C,yBACKA,GADL;IAMEU,UAAU,EAAE;EANd;AAQD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/index.js b/node_modules/@babel/core/lib/transformation/index.js new file mode 100644 index 0000000..17f8e31 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/index.js @@ -0,0 +1,131 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = run; + +function _traverse() { + const data = require("@babel/traverse"); + + _traverse = function () { + return data; + }; + + return data; +} + +var _pluginPass = require("./plugin-pass"); + +var _blockHoistPlugin = require("./block-hoist-plugin"); + +var _normalizeOpts = require("./normalize-opts"); + +var _normalizeFile = require("./normalize-file"); + +var _generate = require("./file/generate"); + +var _deepArray = require("../config/helpers/deep-array"); + +function* run(config, code, ast) { + const file = yield* (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast); + const opts = file.opts; + + try { + yield* transformFile(file, config.passes); + } catch (e) { + var _opts$filename; + + e.message = `${(_opts$filename = opts.filename) != null ? _opts$filename : "unknown file"}: ${e.message}`; + + if (!e.code) { + e.code = "BABEL_TRANSFORM_ERROR"; + } + + throw e; + } + + let outputCode, outputMap; + + try { + if (opts.code !== false) { + ({ + outputCode, + outputMap + } = (0, _generate.default)(config.passes, file)); + } + } catch (e) { + var _opts$filename2; + + e.message = `${(_opts$filename2 = opts.filename) != null ? _opts$filename2 : "unknown file"}: ${e.message}`; + + if (!e.code) { + e.code = "BABEL_GENERATE_ERROR"; + } + + throw e; + } + + return { + metadata: file.metadata, + options: opts, + ast: opts.ast === true ? file.ast : null, + code: outputCode === undefined ? null : outputCode, + map: outputMap === undefined ? null : outputMap, + sourceType: file.ast.program.sourceType, + externalDependencies: (0, _deepArray.flattenToSet)(config.externalDependencies) + }; +} + +function* transformFile(file, pluginPasses) { + for (const pluginPairs of pluginPasses) { + const passPairs = []; + const passes = []; + const visitors = []; + + for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) { + const pass = new _pluginPass.default(file, plugin.key, plugin.options); + passPairs.push([plugin, pass]); + passes.push(pass); + visitors.push(plugin.visitor); + } + + for (const [plugin, pass] of passPairs) { + const fn = plugin.pre; + + if (fn) { + const result = fn.call(pass, file); + yield* []; + + if (isThenable(result)) { + throw new Error(`You appear to be using an plugin with an async .pre, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + } + } + + const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod); + + (0, _traverse().default)(file.ast, visitor, file.scope); + + for (const [plugin, pass] of passPairs) { + const fn = plugin.post; + + if (fn) { + const result = fn.call(pass, file); + yield* []; + + if (isThenable(result)) { + throw new Error(`You appear to be using an plugin with an async .post, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`); + } + } + } + } +} + +function isThenable(val) { + return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function"; +} + +0 && 0; + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/core/lib/transformation/index.js.map b/node_modules/@babel/core/lib/transformation/index.js.map new file mode 100644 index 0000000..1580118 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["run","config","code","ast","file","normalizeFile","passes","normalizeOptions","opts","transformFile","e","message","filename","outputCode","outputMap","generateCode","metadata","options","undefined","map","sourceType","program","externalDependencies","flattenToSet","pluginPasses","pluginPairs","passPairs","visitors","plugin","concat","loadBlockHoistPlugin","pass","PluginPass","key","push","visitor","fn","pre","result","call","isThenable","Error","traverse","merge","wrapPluginVisitorMethod","scope","post","val","then"],"sources":["../../src/transformation/index.ts"],"sourcesContent":["import traverse from \"@babel/traverse\";\nimport type * as t from \"@babel/types\";\ntype SourceMap = any;\nimport type { Handler } from \"gensync\";\n\nimport type { ResolvedConfig, Plugin, PluginPasses } from \"../config\";\n\nimport PluginPass from \"./plugin-pass\";\nimport loadBlockHoistPlugin from \"./block-hoist-plugin\";\nimport normalizeOptions from \"./normalize-opts\";\nimport normalizeFile from \"./normalize-file\";\n\nimport generateCode from \"./file/generate\";\nimport type File from \"./file/file\";\n\nimport { flattenToSet } from \"../config/helpers/deep-array\";\n\nexport type FileResultCallback = {\n (err: Error, file: null): void;\n (err: null, file: FileResult | null): void;\n};\n\nexport type FileResult = {\n metadata: { [key: string]: any };\n options: { [key: string]: any };\n ast: t.File | null;\n code: string | null;\n map: SourceMap | null;\n sourceType: \"script\" | \"module\";\n externalDependencies: Set;\n};\n\nexport function* run(\n config: ResolvedConfig,\n code: string,\n ast?: t.File | t.Program | null,\n): Handler {\n const file = yield* normalizeFile(\n config.passes,\n normalizeOptions(config),\n code,\n ast,\n );\n\n const opts = file.opts;\n try {\n yield* transformFile(file, config.passes);\n } catch (e) {\n e.message = `${opts.filename ?? \"unknown file\"}: ${e.message}`;\n if (!e.code) {\n e.code = \"BABEL_TRANSFORM_ERROR\";\n }\n throw e;\n }\n\n let outputCode, outputMap;\n try {\n if (opts.code !== false) {\n ({ outputCode, outputMap } = generateCode(config.passes, file));\n }\n } catch (e) {\n e.message = `${opts.filename ?? \"unknown file\"}: ${e.message}`;\n if (!e.code) {\n e.code = \"BABEL_GENERATE_ERROR\";\n }\n throw e;\n }\n\n return {\n metadata: file.metadata,\n options: opts,\n ast: opts.ast === true ? file.ast : null,\n code: outputCode === undefined ? null : outputCode,\n map: outputMap === undefined ? null : outputMap,\n sourceType: file.ast.program.sourceType,\n externalDependencies: flattenToSet(config.externalDependencies),\n };\n}\n\nfunction* transformFile(file: File, pluginPasses: PluginPasses): Handler {\n for (const pluginPairs of pluginPasses) {\n const passPairs: [Plugin, PluginPass][] = [];\n const passes = [];\n const visitors = [];\n\n for (const plugin of pluginPairs.concat([loadBlockHoistPlugin()])) {\n const pass = new PluginPass(file, plugin.key, plugin.options);\n\n passPairs.push([plugin, pass]);\n passes.push(pass);\n visitors.push(plugin.visitor);\n }\n\n for (const [plugin, pass] of passPairs) {\n const fn = plugin.pre;\n if (fn) {\n const result = fn.call(pass, file);\n\n // @ts-expect-error - If we want to support async .pre\n yield* [];\n\n if (isThenable(result)) {\n throw new Error(\n `You appear to be using an plugin with an async .pre, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, you may need to upgrade ` +\n `your @babel/core version.`,\n );\n }\n }\n }\n\n // merge all plugin visitors into a single visitor\n const visitor = traverse.visitors.merge(\n visitors,\n passes,\n file.opts.wrapPluginVisitorMethod,\n );\n traverse(file.ast, visitor, file.scope);\n\n for (const [plugin, pass] of passPairs) {\n const fn = plugin.post;\n if (fn) {\n const result = fn.call(pass, file);\n\n // @ts-expect-error - If we want to support async .post\n yield* [];\n\n if (isThenable(result)) {\n throw new Error(\n `You appear to be using an plugin with an async .post, ` +\n `which your current version of Babel does not support. ` +\n `If you're using a published plugin, you may need to upgrade ` +\n `your @babel/core version.`,\n );\n }\n }\n }\n }\n}\n\nfunction isThenable>(val: any): val is T {\n return (\n !!val &&\n (typeof val === \"object\" || typeof val === \"function\") &&\n !!val.then &&\n typeof val.then === \"function\"\n );\n}\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAOA;;AACA;;AACA;;AACA;;AAEA;;AAGA;;AAiBO,UAAUA,GAAV,CACLC,MADK,EAELC,IAFK,EAGLC,GAHK,EAIgB;EACrB,MAAMC,IAAI,GAAG,OAAO,IAAAC,sBAAA,EAClBJ,MAAM,CAACK,MADW,EAElB,IAAAC,sBAAA,EAAiBN,MAAjB,CAFkB,EAGlBC,IAHkB,EAIlBC,GAJkB,CAApB;EAOA,MAAMK,IAAI,GAAGJ,IAAI,CAACI,IAAlB;;EACA,IAAI;IACF,OAAOC,aAAa,CAACL,IAAD,EAAOH,MAAM,CAACK,MAAd,CAApB;EACD,CAFD,CAEE,OAAOI,CAAP,EAAU;IAAA;;IACVA,CAAC,CAACC,OAAF,GAAa,GAAD,kBAAGH,IAAI,CAACI,QAAR,6BAAoB,cAAe,KAAIF,CAAC,CAACC,OAAQ,EAA7D;;IACA,IAAI,CAACD,CAAC,CAACR,IAAP,EAAa;MACXQ,CAAC,CAACR,IAAF,GAAS,uBAAT;IACD;;IACD,MAAMQ,CAAN;EACD;;EAED,IAAIG,UAAJ,EAAgBC,SAAhB;;EACA,IAAI;IACF,IAAIN,IAAI,CAACN,IAAL,KAAc,KAAlB,EAAyB;MACvB,CAAC;QAAEW,UAAF;QAAcC;MAAd,IAA4B,IAAAC,i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AP,KAAe,QAAf,IAA2B,OAAOA,GAAP,KAAe,UAD3C,KAEA,CAAC,CAACA,GAAG,CAACC,IAFN,IAGA,OAAOD,GAAG,CAACC,IAAX,KAAoB,UAJtB;AAMD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/normalize-file.js b/node_modules/@babel/core/lib/transformation/normalize-file.js new file mode 100644 index 0000000..98a8f0a --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/normalize-file.js @@ -0,0 +1,171 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = normalizeFile; + +function _fs() { + const data = require("fs"); + + _fs = function () { + return data; + }; + + return data; +} + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _debug() { + const data = require("debug"); + + _debug = function () { + return data; + }; + + return data; +} + +function _t() { + const data = require("@babel/types"); + + _t = function () { + return data; + }; + + return data; +} + +function _convertSourceMap() { + const data = require("convert-source-map"); + + _convertSourceMap = function () { + return data; + }; + + return data; +} + +var _file = require("./file/file"); + +var _parser = require("../parser"); + +var _cloneDeep = require("./util/clone-deep"); + +const { + file, + traverseFast +} = _t(); + +const debug = _debug()("babel:transform:file"); + +const LARGE_INPUT_SOURCEMAP_THRESHOLD = 3000000; + +function* normalizeFile(pluginPasses, options, code, ast) { + code = `${code || ""}`; + + if (ast) { + if (ast.type === "Program") { + ast = file(ast, [], []); + } else if (ast.type !== "File") { + throw new Error("AST root must be a Program or File node"); + } + + if (options.cloneInputAst) { + ast = (0, _cloneDeep.default)(ast); + } + } else { + ast = yield* (0, _parser.default)(pluginPasses, options, code); + } + + let inputMap = null; + + if (options.inputSourceMap !== false) { + if (typeof options.inputSourceMap === "object") { + inputMap = _convertSourceMap().fromObject(options.inputSourceMap); + } + + if (!inputMap) { + const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast); + + if (lastComment) { + try { + inputMap = _convertSourceMap().fromComment(lastComment); + } catch (err) { + debug("discarding unknown inline input sourcemap", err); + } + } + } + + if (!inputMap) { + const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast); + + if (typeof options.filename === "string" && lastComment) { + try { + const match = EXTERNAL_SOURCEMAP_REGEX.exec(lastComment); + + const inputMapContent = _fs().readFileSync(_path().resolve(_path().dirname(options.filename), match[1])); + + if (inputMapContent.length > LARGE_INPUT_SOURCEMAP_THRESHOLD) { + debug("skip merging input map > 1 MB"); + } else { + inputMap = _convertSourceMap().fromJSON(inputMapContent); + } + } catch (err) { + debug("discarding unknown file input sourcemap", err); + } + } else if (lastComment) { + debug("discarding un-loadable file input sourcemap"); + } + } + } + + return new _file.default(options, { + code, + ast: ast, + inputMap + }); +} + +const INLINE_SOURCEMAP_REGEX = /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/; +const EXTERNAL_SOURCEMAP_REGEX = /^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/; + +function extractCommentsFromList(regex, comments, lastComment) { + if (comments) { + comments = comments.filter(({ + value + }) => { + if (regex.test(value)) { + lastComment = value; + return false; + } + + return true; + }); + } + + return [comments, lastComment]; +} + +function extractComments(regex, ast) { + let lastComment = null; + traverseFast(ast, node => { + [node.leadingComments, lastComment] = extractCommentsFromList(regex, node.leadingComments, lastComment); + [node.innerComments, lastComment] = extractCommentsFromList(regex, node.innerComments, lastComment); + [node.trailingComments, lastComment] = extractCommentsFromList(regex, node.trailingComments, lastComment); + }); + return lastComment; +} + +0 && 0; + +//# sourceMappingURL=normalize-file.js.map diff --git a/node_modules/@babel/core/lib/transformation/normalize-file.js.map b/node_modules/@babel/core/lib/transformation/normalize-file.js.map new file mode 100644 index 0000000..bf51151 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/normalize-file.js.map @@ -0,0 +1 @@ +{"version":3,"names":["file","traverseFast","debug","buildDebug","LARGE_INPUT_SOURCEMAP_THRESHOLD","normalizeFile","pluginPasses","options","code","ast","type","Error","cloneInputAst","cloneDeep","parser","inputMap","inputSourceMap","convertSourceMap","fromObject","lastComment","extractComments","INLINE_SOURCEMAP_REGEX","fromComment","err","EXTERNAL_SOURCEMAP_REGEX","filename","match","exec","inputMapContent","fs","readFileSync","path","resolve","dirname","length","fromJSON","File","extractCommentsFromList","regex","comments","filter","value","test","node","leadingComments","innerComments","trailingComments"],"sources":["../../src/transformation/normalize-file.ts"],"sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport buildDebug from \"debug\";\nimport type { Handler } from \"gensync\";\nimport { file, traverseFast } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport type { PluginPasses } from \"../config\";\nimport convertSourceMap from \"convert-source-map\";\nimport type { SourceMapConverter as Converter } from \"convert-source-map\";\nimport File from \"./file/file\";\nimport parser from \"../parser\";\nimport cloneDeep from \"./util/clone-deep\";\n\nconst debug = buildDebug(\"babel:transform:file\");\nconst LARGE_INPUT_SOURCEMAP_THRESHOLD = 3_000_000;\n\nexport type NormalizedFile = {\n code: string;\n ast: t.File;\n inputMap: Converter | null;\n};\n\nexport default function* normalizeFile(\n pluginPasses: PluginPasses,\n options: { [key: string]: any },\n code: string,\n ast?: t.File | t.Program | null,\n): Handler {\n code = `${code || \"\"}`;\n\n if (ast) {\n if (ast.type === \"Program\") {\n ast = file(ast, [], []);\n } else if (ast.type !== \"File\") {\n throw new Error(\"AST root must be a Program or File node\");\n }\n\n if (options.cloneInputAst) {\n ast = cloneDeep(ast) as t.File;\n }\n } else {\n // @ts-expect-error todo: use babel-types ast typings in Babel parser\n ast = yield* parser(pluginPasses, options, code);\n }\n\n let inputMap = null;\n if (options.inputSourceMap !== false) {\n // If an explicit object is passed in, it overrides the processing of\n // source maps that may be in the file itself.\n if (typeof options.inputSourceMap === \"object\") {\n inputMap = convertSourceMap.fromObject(options.inputSourceMap);\n }\n\n if (!inputMap) {\n const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast);\n if (lastComment) {\n try {\n inputMap = convertSourceMap.fromComment(lastComment);\n } catch (err) {\n debug(\"discarding unknown inline input sourcemap\", err);\n }\n }\n }\n\n if (!inputMap) {\n const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast);\n if (typeof options.filename === \"string\" && lastComment) {\n try {\n // when `lastComment` is non-null, EXTERNAL_SOURCEMAP_REGEX must have matches\n const match: [string, string] = EXTERNAL_SOURCEMAP_REGEX.exec(\n lastComment,\n ) as any;\n const inputMapContent = fs.readFileSync(\n path.resolve(path.dirname(options.filename), match[1]),\n );\n if (inputMapContent.length > LARGE_INPUT_SOURCEMAP_THRESHOLD) {\n debug(\"skip merging input map > 1 MB\");\n } else {\n inputMap = convertSourceMap.fromJSON(\n // todo:\n inputMapContent as unknown as string,\n );\n }\n } catch (err) {\n debug(\"discarding unknown file input sourcemap\", err);\n }\n } else if (lastComment) {\n debug(\"discarding un-loadable file input sourcemap\");\n }\n }\n }\n\n return new File(options, {\n code,\n ast: ast as t.File,\n inputMap,\n });\n}\n\n// These regexps are copied from the convert-source-map package,\n// but without // or /* at the beginning of the comment.\n\n// eslint-disable-next-line max-len\nconst INLINE_SOURCEMAP_REGEX =\n /^[@#]\\s+sourceMappingURL=data:(?:application|text)\\/json;(?:charset[:=]\\S+?;)?base64,(?:.*)$/;\nconst EXTERNAL_SOURCEMAP_REGEX =\n /^[@#][ \\t]+sourceMappingURL=([^\\s'\"`]+)[ \\t]*$/;\n\nfunction extractCommentsFromList(\n regex: RegExp,\n comments: t.Comment[],\n lastComment: string | null,\n): [t.Comment[], string | null] {\n if (comments) {\n comments = comments.filter(({ value }) => {\n if (regex.test(value)) {\n lastComment = value;\n return false;\n }\n return true;\n });\n }\n return [comments, lastComment];\n}\n\nfunction extractComments(regex: RegExp, ast: t.Node) {\n let lastComment: string = null;\n traverseFast(ast, node => {\n [node.leadingComments, lastComment] = extractCommentsFromList(\n regex,\n node.leadingComments,\n lastComment,\n );\n [node.innerComments, lastComment] = extractCommentsFromList(\n regex,\n node.innerComments,\n lastComment,\n );\n [node.trailingComments, last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AHuB,CAAlB,CAAP;AAKD;;AAMD,MAAMM,sBAAsB,GAC1B,8FADF;AAEA,MAAMG,wBAAwB,GAC5B,gDADF;;AAGA,SAASa,uBAAT,CACEC,KADF,EAEEC,QAFF,EAGEpB,WAHF,EAIgC;EAC9B,IAAIoB,QAAJ,EAAc;IACZA,QAAQ,GAAGA,QAAQ,CAACC,MAAT,CAAgB,CAAC;MAAEC;IAAF,CAAD,KAAe;MACxC,IAAIH,KAAK,CAACI,IAAN,CAAWD,KAAX,CAAJ,EAAuB;QACrBtB,WAAW,GAAGsB,KAAd;QACA,OAAO,KAAP;MACD;;MACD,OAAO,IAAP;IACD,CANU,CAAX;EAOD;;EACD,OAAO,CAACF,QAAD,EAAWpB,WAAX,CAAP;AACD;;AAED,SAASC,eAAT,CAAyBkB,KAAzB,EAAwC7B,GAAxC,EAAqD;EACnD,IAAIU,WAAmB,GAAG,IAA1B;EACAlB,YAAY,CAACQ,GAAD,EAAMkC,IAAI,IAAI;IACxB,CAACA,IAAI,CAACC,eAAN,EAAuBzB,WAAvB,IAAsCkB,uBAAuB,CAC3DC,KAD2D,EAE3DK,IAAI,CAACC,eAFsD,EAG3DzB,WAH2D,CAA7D;IAKA,CAACwB,IAAI,CAACE,aAAN,EAAqB1B,WAArB,IAAoCkB,uBAAuB,CACzDC,KADyD,EAEzDK,IAAI,CAACE,aAFoD,EAGzD1B,WAHyD,CAA3D;IAKA,CAACwB,IAAI,CAACG,gBAAN,EAAwB3B,WAAxB,IAAuCkB,uBAAuB,CAC5DC,KAD4D,EAE5DK,IAAI,CAACG,gBAFuD,EAG5D3B,WAH4D,CAA9D;EAKD,CAhBW,CAAZ;EAiBA,OAAOA,WAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/normalize-opts.js b/node_modules/@babel/core/lib/transformation/normalize-opts.js new file mode 100644 index 0000000..1f0656e --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/normalize-opts.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = normalizeOptions; + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function normalizeOptions(config) { + const { + filename, + cwd, + filenameRelative = typeof filename === "string" ? _path().relative(cwd, filename) : "unknown", + sourceType = "module", + inputSourceMap, + sourceMaps = !!inputSourceMap, + sourceRoot = config.options.moduleRoot, + sourceFileName = _path().basename(filenameRelative), + comments = true, + compact = "auto" + } = config.options; + const opts = config.options; + const options = Object.assign({}, opts, { + parserOpts: Object.assign({ + sourceType: _path().extname(filenameRelative) === ".mjs" ? "module" : sourceType, + sourceFileName: filename, + plugins: [] + }, opts.parserOpts), + generatorOpts: Object.assign({ + filename, + auxiliaryCommentBefore: opts.auxiliaryCommentBefore, + auxiliaryCommentAfter: opts.auxiliaryCommentAfter, + retainLines: opts.retainLines, + comments, + shouldPrintComment: opts.shouldPrintComment, + compact, + minified: opts.minified, + sourceMaps, + sourceRoot, + sourceFileName + }, opts.generatorOpts) + }); + + for (const plugins of config.passes) { + for (const plugin of plugins) { + if (plugin.manipulateOptions) { + plugin.manipulateOptions(options, options.parserOpts); + } + } + } + + return options; +} + +0 && 0; + +//# sourceMappingURL=normalize-opts.js.map diff --git a/node_modules/@babel/core/lib/transformation/normalize-opts.js.map b/node_modules/@babel/core/lib/transformation/normalize-opts.js.map new file mode 100644 index 0000000..f679f93 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/normalize-opts.js.map @@ -0,0 +1 @@ +{"version":3,"names":["normalizeOptions","config","filename","cwd","filenameRelative","path","relative","sourceType","inputSourceMap","sourceMaps","sourceRoot","options","moduleRoot","sourceFileName","basename","comments","compact","opts","parserOpts","extname","plugins","generatorOpts","auxiliaryCommentBefore","auxiliaryCommentAfter","retainLines","shouldPrintComment","minified","passes","plugin","manipulateOptions"],"sources":["../../src/transformation/normalize-opts.ts"],"sourcesContent":["import path from \"path\";\nimport type { ResolvedConfig } from \"../config\";\n\nexport default function normalizeOptions(config: ResolvedConfig): {} {\n const {\n filename,\n cwd,\n filenameRelative = typeof filename === \"string\"\n ? path.relative(cwd, filename)\n : \"unknown\",\n sourceType = \"module\",\n inputSourceMap,\n sourceMaps = !!inputSourceMap,\n sourceRoot = process.env.BABEL_8_BREAKING\n ? undefined\n : config.options.moduleRoot,\n\n sourceFileName = path.basename(filenameRelative),\n\n comments = true,\n compact = \"auto\",\n } = config.options;\n\n const opts = config.options;\n\n const options = {\n ...opts,\n\n parserOpts: {\n sourceType:\n path.extname(filenameRelative) === \".mjs\" ? \"module\" : sourceType,\n\n sourceFileName: filename,\n plugins: [],\n ...opts.parserOpts,\n },\n\n generatorOpts: {\n // General generator flags.\n filename,\n\n auxiliaryCommentBefore: opts.auxiliaryCommentBefore,\n auxiliaryCommentAfter: opts.auxiliaryCommentAfter,\n retainLines: opts.retainLines,\n comments,\n shouldPrintComment: opts.shouldPrintComment,\n compact,\n minified: opts.minified,\n\n // Source-map generation flags.\n sourceMaps,\n\n sourceRoot,\n sourceFileName,\n ...opts.generatorOpts,\n },\n };\n\n for (const plugins of config.passes) {\n for (const plugin of plugins) {\n if (plugin.manipulateOptions) {\n plugin.manipulateOptions(options, options.parserOpts);\n }\n }\n }\n\n return options;\n}\n"],"mappings":";;;;;;;AAAA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AAGe,SAASA,gBAAT,CAA0BC,MAA1B,EAAsD;EACnE,MAAM;IACJC,QADI;IAEJC,GAFI;IAGJC,gBAAgB,GAAG,OAAOF,QAAP,KAAoB,QAApB,GACfG,OAAA,CAAKC,QAAL,CAAcH,GAAd,EAAmBD,QAAnB,CADe,GAEf,SALA;IAMJK,UAAU,GAAG,QANT;IAOJC,cAPI;IAQJC,UAAU,GAAG,CAAC,CAACD,cARX;IASJE,UAAU,GAENT,MAAM,CAACU,OAAP,CAAeC,UAXf;IAaJC,cAAc,GAAGR,OAAA,CAAKS,QAAL,CAAcV,gBAAd,CAbb;IAeJW,QAAQ,GAAG,IAfP;IAgBJC,OAAO,GAAG;EAhBN,IAiBFf,MAAM,CAACU,OAjBX;EAmBA,MAAMM,IAAI,GAAGhB,MAAM,CAACU,OAApB;EAEA,MAAMA,OAAO,qBACRM,IADQ;IAGXC,UAAU;MACRX,UAAU,EACRF,OAAA,CAAKc,OAAL,CAAaf,gBAAb,MAAmC,MAAnC,GAA4C,QAA5C,GAAuDG,UAFjD;MAIRM,cAAc,EAAEX,QAJR;MAKRkB,OAAO,EAAE;IALD,GAMLH,IAAI,CAACC,UANA,CAHC;IAYXG,aAAa;MAEXnB,QAFW;MAIXoB,sBAAsB,EAAEL,IAAI,CAACK,sBAJlB;MAKXC,qBAAqB,EAAEN,IAAI,CAACM,qBALjB;MAMXC,WAAW,EAAEP,IAAI,CAACO,WANP;MAOXT,QAPW;MAQXU,kBAAkB,EAAER,IAAI,CAACQ,kBARd;MASXT,OATW;MAUXU,QAAQ,EAAET,IAAI,CAACS,QAVJ;MAaXjB,UAbW;MAeXC,UAfW;MAgBXG;IAhBW,GAiBRI,IAAI,CAACI,aAjBG;EAZF,EAAb;;EAiCA,KAAK,MAAMD,OAAX,IAAsBnB,MAAM,CAAC0B,MAA7B,EAAqC;IACnC,KAAK,MAAMC,MAAX,IAAqBR,OAArB,EAA8B;MAC5B,IAAIQ,MAAM,CAACC,iBAAX,EAA8B;QAC5BD,MAAM,CAACC,iBAAP,CAAyBlB,OAAzB,EAAkCA,OAAO,CAACO,UAA1C;MACD;IACF;EACF;;EAED,OAAOP,OAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/plugin-pass.js b/node_modules/@babel/core/lib/transformation/plugin-pass.js new file mode 100644 index 0000000..c49cfe6 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/plugin-pass.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +class PluginPass { + constructor(file, key, options) { + this._map = new Map(); + this.key = void 0; + this.file = void 0; + this.opts = void 0; + this.cwd = void 0; + this.filename = void 0; + this.key = key; + this.file = file; + this.opts = options || {}; + this.cwd = file.opts.cwd; + this.filename = file.opts.filename; + } + + set(key, val) { + this._map.set(key, val); + } + + get(key) { + return this._map.get(key); + } + + availableHelper(name, versionRange) { + return this.file.availableHelper(name, versionRange); + } + + addHelper(name) { + return this.file.addHelper(name); + } + + addImport() { + return this.file.addImport(); + } + + buildCodeFrameError(node, msg, _Error) { + return this.file.buildCodeFrameError(node, msg, _Error); + } + +} + +exports.default = PluginPass; +{ + PluginPass.prototype.getModuleName = function getModuleName() { + return this.file.getModuleName(); + }; +} +0 && 0; + +//# sourceMappingURL=plugin-pass.js.map diff --git a/node_modules/@babel/core/lib/transformation/plugin-pass.js.map b/node_modules/@babel/core/lib/transformation/plugin-pass.js.map new file mode 100644 index 0000000..ecb970f --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/plugin-pass.js.map @@ -0,0 +1 @@ +{"version":3,"names":["PluginPass","constructor","file","key","options","_map","Map","opts","cwd","filename","set","val","get","availableHelper","name","versionRange","addHelper","addImport","buildCodeFrameError","node","msg","_Error","prototype","getModuleName"],"sources":["../../src/transformation/plugin-pass.ts"],"sourcesContent":["import type File from \"./file/file\";\nimport type { NodeLocation } from \"./file/file\";\n\nexport default class PluginPass {\n _map: Map = new Map();\n key: string | undefined | null;\n file: File;\n opts: any;\n\n // The working directory that Babel's programmatic options are loaded\n // relative to.\n cwd: string;\n\n // The absolute path of the file being compiled.\n filename: string | void;\n\n constructor(file: File, key?: string | null, options?: any | null) {\n this.key = key;\n this.file = file;\n this.opts = options || {};\n this.cwd = file.opts.cwd;\n this.filename = file.opts.filename;\n }\n\n set(key: unknown, val: unknown) {\n this._map.set(key, val);\n }\n\n get(key: unknown): any {\n return this._map.get(key);\n }\n\n availableHelper(name: string, versionRange?: string | null) {\n return this.file.availableHelper(name, versionRange);\n }\n\n addHelper(name: string) {\n return this.file.addHelper(name);\n }\n\n addImport() {\n return this.file.addImport();\n }\n\n buildCodeFrameError(\n node: NodeLocation | undefined | null,\n msg: string,\n _Error?: typeof Error,\n ) {\n return this.file.buildCodeFrameError(node, msg, _Error);\n }\n}\n\nif (!process.env.BABEL_8_BREAKING) {\n (PluginPass as any).prototype.getModuleName = function getModuleName():\n | string\n | undefined {\n return this.file.getModuleName();\n };\n}\n"],"mappings":";;;;;;;AAGe,MAAMA,UAAN,CAAiB;EAa9BC,WAAW,CAACC,IAAD,EAAaC,GAAb,EAAkCC,OAAlC,EAAwD;IAAA,KAZnEC,IAYmE,GAZrC,IAAIC,GAAJ,EAYqC;IAAA,KAXnEH,GAWmE;IAAA,KAVnED,IAUmE;IAAA,KATnEK,IASmE;IAAA,KALnEC,GAKmE;IAAA,KAFnEC,QAEmE;IACjE,KAAKN,GAAL,GAAWA,GAAX;IACA,KAAKD,IAAL,GAAYA,IAAZ;IACA,KAAKK,IAAL,GAAYH,OAAO,IAAI,EAAvB;IACA,KAAKI,GAAL,GAAWN,IAAI,CAACK,IAAL,CAAUC,GAArB;IACA,KAAKC,QAAL,GAAgBP,IAAI,CAACK,IAAL,CAAUE,QAA1B;EACD;;EAEDC,GAAG,CAACP,GAAD,EAAeQ,GAAf,EAA6B;IAC9B,KAAKN,IAAL,CAAUK,GAAV,CAAcP,GAAd,EAAmBQ,GAAnB;EACD;;EAEDC,GAAG,CAACT,GAAD,EAAoB;IACrB,OAAO,KAAKE,IAAL,CAAUO,GAAV,CAAcT,GAAd,CAAP;EACD;;EAEDU,eAAe,CAACC,IAAD,EAAeC,YAAf,EAA6C;IAC1D,OAAO,KAAKb,IAAL,CAAUW,eAAV,CAA0BC,IAA1B,EAAgCC,YAAhC,CAAP;EACD;;EAEDC,SAAS,CAACF,IAAD,EAAe;IACtB,OAAO,KAAKZ,IAAL,CAAUc,SAAV,CAAoBF,IAApB,CAAP;EACD;;EAEDG,SAAS,GAAG;IACV,OAAO,KAAKf,IAAL,CAAUe,SAAV,EAAP;EACD;;EAEDC,mBAAmB,CACjBC,IADiB,EAEjBC,GAFiB,EAGjBC,MAHiB,EAIjB;IACA,OAAO,KAAKnB,IAAL,CAAUgB,mBAAV,CAA8BC,IAA9B,EAAoCC,GAApC,EAAyCC,MAAzC,CAAP;EACD;;AA/C6B;;;AAkDG;EAChCrB,UAAD,CAAoBsB,SAApB,CAA8BC,aAA9B,GAA8C,SAASA,aAAT,GAEhC;IACZ,OAAO,KAAKrB,IAAL,CAAUqB,aAAV,EAAP;EACD,CAJD;AAKD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/transformation/util/clone-deep.js b/node_modules/@babel/core/lib/transformation/util/clone-deep.js new file mode 100644 index 0000000..bce456c --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/util/clone-deep.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = _default; + +function deepClone(value, cache) { + if (value !== null) { + if (cache.has(value)) return cache.get(value); + let cloned; + + if (Array.isArray(value)) { + cloned = new Array(value.length); + + for (let i = 0; i < value.length; i++) { + cloned[i] = typeof value[i] !== "object" ? value[i] : deepClone(value[i], cache); + } + } else { + cloned = {}; + const keys = Object.keys(value); + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + cloned[key] = typeof value[key] !== "object" ? value[key] : deepClone(value[key], cache); + } + } + + cache.set(value, cloned); + return cloned; + } + + return value; +} + +function _default(value) { + if (typeof value !== "object") return value; + return deepClone(value, new Map()); +} + +0 && 0; + +//# sourceMappingURL=clone-deep.js.map diff --git a/node_modules/@babel/core/lib/transformation/util/clone-deep.js.map b/node_modules/@babel/core/lib/transformation/util/clone-deep.js.map new file mode 100644 index 0000000..1675076 --- /dev/null +++ b/node_modules/@babel/core/lib/transformation/util/clone-deep.js.map @@ -0,0 +1 @@ +{"version":3,"names":["deepClone","value","cache","has","get","cloned","Array","isArray","length","i","keys","Object","key","set","Map"],"sources":["../../../src/transformation/util/clone-deep.ts"],"sourcesContent":["//https://github.com/babel/babel/pull/14583#discussion_r882828856\nfunction deepClone(value: any, cache: Map): any {\n if (value !== null) {\n if (cache.has(value)) return cache.get(value);\n let cloned: any;\n if (Array.isArray(value)) {\n cloned = new Array(value.length);\n for (let i = 0; i < value.length; i++) {\n cloned[i] =\n typeof value[i] !== \"object\" ? value[i] : deepClone(value[i], cache);\n }\n } else {\n cloned = {};\n const keys = Object.keys(value);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n cloned[key] =\n typeof value[key] !== \"object\"\n ? value[key]\n : deepClone(value[key], cache);\n }\n }\n cache.set(value, cloned);\n return cloned;\n }\n return value;\n}\n\nexport default function (value: T): T {\n if (typeof value !== \"object\") return value;\n return deepClone(value, new Map());\n}\n"],"mappings":";;;;;;;AACA,SAASA,SAAT,CAAmBC,KAAnB,EAA+BC,KAA/B,EAA0D;EACxD,IAAID,KAAK,KAAK,IAAd,EAAoB;IAClB,IAAIC,KAAK,CAACC,GAAN,CAAUF,KAAV,CAAJ,EAAsB,OAAOC,KAAK,CAACE,GAAN,CAAUH,KAAV,CAAP;IACtB,IAAII,MAAJ;;IACA,IAAIC,KAAK,CAACC,OAAN,CAAcN,KAAd,CAAJ,EAA0B;MACxBI,MAAM,GAAG,IAAIC,KAAJ,CAAUL,KAAK,CAACO,MAAhB,CAAT;;MACA,KAAK,IAAIC,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGR,KAAK,CAACO,MAA1B,EAAkCC,CAAC,EAAnC,EAAuC;QACrCJ,MAAM,CAACI,CAAD,CAAN,GACE,OAAOR,KAAK,CAACQ,CAAD,CAAZ,KAAoB,QAApB,GAA+BR,KAAK,CAACQ,CAAD,CAApC,GAA0CT,SAAS,CAACC,KAAK,CAACQ,CAAD,CAAN,EAAWP,KAAX,CADrD;MAED;IACF,CAND,MAMO;MACLG,MAAM,GAAG,EAAT;MACA,MAAMK,IAAI,GAAGC,MAAM,CAACD,IAAP,CAAYT,KAAZ,CAAb;;MACA,KAAK,IAAIQ,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGC,IAAI,CAACF,MAAzB,EAAiCC,CAAC,EAAlC,EAAsC;QACpC,MAAMG,GAAG,GAAGF,IAAI,CAACD,CAAD,CAAhB;QACAJ,MAAM,CAACO,GAAD,CAAN,GACE,OAAOX,KAAK,CAACW,GAAD,CAAZ,KAAsB,QAAtB,GACIX,KAAK,CAACW,GAAD,CADT,GAEIZ,SAAS,CAACC,KAAK,CAACW,GAAD,CAAN,EAAaV,KAAb,CAHf;MAID;IACF;;IACDA,KAAK,CAACW,GAAN,CAAUZ,KAAV,EAAiBI,MAAjB;IACA,OAAOA,MAAP;EACD;;EACD,OAAOJ,KAAP;AACD;;AAEc,kBAAaA,KAAb,EAA0B;EACvC,IAAI,OAAOA,KAAP,KAAiB,QAArB,EAA+B,OAAOA,KAAP;EAC/B,OAAOD,SAAS,CAACC,KAAD,EAAQ,IAAIa,GAAJ,EAAR,CAAhB;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/core/lib/vendor/import-meta-resolve.js b/node_modules/@babel/core/lib/vendor/import-meta-resolve.js new file mode 100644 index 0000000..637019e --- /dev/null +++ b/node_modules/@babel/core/lib/vendor/import-meta-resolve.js @@ -0,0 +1,3559 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.moduleResolve = moduleResolve; +exports.resolve = resolve; + +function _url() { + const data = require("url"); + + _url = function () { + return data; + }; + + return data; +} + +function _fs() { + const data = _interopRequireWildcard(require("fs"), true); + + _fs = function () { + return data; + }; + + return data; +} + +function _path() { + const data = require("path"); + + _path = function () { + return data; + }; + + return data; +} + +function _assert() { + const data = require("assert"); + + _assert = function () { + return data; + }; + + return data; +} + +function _util() { + const data = require("util"); + + _util = function () { + return data; + }; + + return data; +} + +function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } + +function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var re$3 = { + exports: {} +}; +const SEMVER_SPEC_VERSION = '2.0.0'; +const MAX_LENGTH$2 = 256; +const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || 9007199254740991; +const MAX_SAFE_COMPONENT_LENGTH = 16; +var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH: MAX_LENGTH$2, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1, + MAX_SAFE_COMPONENT_LENGTH +}; +const debug$1 = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {}; +var debug_1 = debug$1; + +(function (module, exports) { + const { + MAX_SAFE_COMPONENT_LENGTH + } = constants; + const debug = debug_1; + exports = module.exports = {}; + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug(name, index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`); + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`); + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`); + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); + createToken('FULLPLAIN', `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); + createToken('FULL', `^${src[t.FULLPLAIN]}$`); + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + createToken('GTLT', '((?:<|>)?=?)'); + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`); + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`); + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); + createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); + createToken('LONETILDE', '(?:~>?)'); + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken('LONECARET', '(?:\\^)'); + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`); + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`); + createToken('STAR', '(<|>)?=?\\s*\\*'); + createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$'); +})(re$3, re$3.exports); + +const opts = ['includePrerelease', 'loose', 'rtl']; + +const parseOptions$2 = options => !options ? {} : typeof options !== 'object' ? { + loose: true +} : opts.filter(k => options[k]).reduce((o, k) => { + o[k] = true; + return o; +}, {}); + +var parseOptions_1 = parseOptions$2; +const numeric = /^[0-9]+$/; + +const compareIdentifiers$1 = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; +}; + +const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a); + +var identifiers = { + compareIdentifiers: compareIdentifiers$1, + rcompareIdentifiers +}; +const debug = debug_1; +const { + MAX_LENGTH: MAX_LENGTH$1, + MAX_SAFE_INTEGER +} = constants; +const { + re: re$2, + t: t$2 +} = re$3.exports; +const parseOptions$1 = parseOptions_1; +const { + compareIdentifiers +} = identifiers; + +class SemVer$c { + constructor(version, options) { + options = parseOptions$1(options); + + if (version instanceof SemVer$c) { + if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`); + } + + if (version.length > MAX_LENGTH$1) { + throw new TypeError(`version is longer than ${MAX_LENGTH$1} characters`); + } + + debug('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + const m = version.trim().match(options.loose ? re$2[t$2.LOOSE] : re$2[t$2.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`); + } + + this.raw = version; + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version'); + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version'); + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version'); + } + + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map(id => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + + return id; + }); + } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format() { + this.version = `${this.major}.${this.minor}.${this.patch}`; + + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; + } + + return this.version; + } + + toString() { + return this.version; + } + + compare(other) { + debug('SemVer.compare', this.version, this.options, other); + + if (!(other instanceof SemVer$c)) { + if (typeof other === 'string' && other === this.version) { + return 0; + } + + other = new SemVer$c(other, this.options); + } + + if (other.version === this.version) { + return 0; + } + + return this.compareMain(other) || this.comparePre(other); + } + + compareMain(other) { + if (!(other instanceof SemVer$c)) { + other = new SemVer$c(other, this.options); + } + + return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); + } + + comparePre(other) { + if (!(other instanceof SemVer$c)) { + other = new SemVer$c(other, this.options); + } + + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + + let i = 0; + + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + + compareBuild(other) { + if (!(other instanceof SemVer$c)) { + other = new SemVer$c(other, this.options); + } + + let i = 0; + + do { + const a = this.build[i]; + const b = other.build[i]; + debug('prerelease compare', i, a, b); + + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + } + + inc(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + + case 'prepatch': + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + + this.inc('pre', identifier); + break; + + case 'major': + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + + case 'minor': + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + + this.patch = 0; + this.prerelease = []; + break; + + case 'patch': + if (this.prerelease.length === 0) { + this.patch++; + } + + this.prerelease = []; + break; + + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + + if (i === -1) { + this.prerelease.push(0); + } + } + + if (identifier) { + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + + break; + + default: + throw new Error(`invalid increment argument: ${release}`); + } + + this.format(); + this.raw = this.version; + return this; + } + +} + +var semver$2 = SemVer$c; +const { + MAX_LENGTH +} = constants; +const { + re: re$1, + t: t$1 +} = re$3.exports; +const SemVer$b = semver$2; +const parseOptions = parseOptions_1; + +const parse$5 = (version, options) => { + options = parseOptions(options); + + if (version instanceof SemVer$b) { + return version; + } + + if (typeof version !== 'string') { + return null; + } + + if (version.length > MAX_LENGTH) { + return null; + } + + const r = options.loose ? re$1[t$1.LOOSE] : re$1[t$1.FULL]; + + if (!r.test(version)) { + return null; + } + + try { + return new SemVer$b(version, options); + } catch (er) { + return null; + } +}; + +var parse_1 = parse$5; +const parse$4 = parse_1; + +const valid$1 = (version, options) => { + const v = parse$4(version, options); + return v ? v.version : null; +}; + +var valid_1 = valid$1; +const parse$3 = parse_1; + +const clean = (version, options) => { + const s = parse$3(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null; +}; + +var clean_1 = clean; +const SemVer$a = semver$2; + +const inc = (version, release, options, identifier) => { + if (typeof options === 'string') { + identifier = options; + options = undefined; + } + + try { + return new SemVer$a(version instanceof SemVer$a ? version.version : version, options).inc(release, identifier).version; + } catch (er) { + return null; + } +}; + +var inc_1 = inc; +const SemVer$9 = semver$2; + +const compare$a = (a, b, loose) => new SemVer$9(a, loose).compare(new SemVer$9(b, loose)); + +var compare_1 = compare$a; +const compare$9 = compare_1; + +const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0; + +var eq_1 = eq$2; +const parse$2 = parse_1; +const eq$1 = eq_1; + +const diff = (version1, version2) => { + if (eq$1(version1, version2)) { + return null; + } else { + const v1 = parse$2(version1); + const v2 = parse$2(version2); + const hasPre = v1.prerelease.length || v2.prerelease.length; + const prefix = hasPre ? 'pre' : ''; + const defaultResult = hasPre ? 'prerelease' : ''; + + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key; + } + } + } + + return defaultResult; + } +}; + +var diff_1 = diff; +const SemVer$8 = semver$2; + +const major = (a, loose) => new SemVer$8(a, loose).major; + +var major_1 = major; +const SemVer$7 = semver$2; + +const minor = (a, loose) => new SemVer$7(a, loose).minor; + +var minor_1 = minor; +const SemVer$6 = semver$2; + +const patch = (a, loose) => new SemVer$6(a, loose).patch; + +var patch_1 = patch; +const parse$1 = parse_1; + +const prerelease = (version, options) => { + const parsed = parse$1(version, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; +}; + +var prerelease_1 = prerelease; +const compare$8 = compare_1; + +const rcompare = (a, b, loose) => compare$8(b, a, loose); + +var rcompare_1 = rcompare; +const compare$7 = compare_1; + +const compareLoose = (a, b) => compare$7(a, b, true); + +var compareLoose_1 = compareLoose; +const SemVer$5 = semver$2; + +const compareBuild$2 = (a, b, loose) => { + const versionA = new SemVer$5(a, loose); + const versionB = new SemVer$5(b, loose); + return versionA.compare(versionB) || versionA.compareBuild(versionB); +}; + +var compareBuild_1 = compareBuild$2; +const compareBuild$1 = compareBuild_1; + +const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose)); + +var sort_1 = sort; +const compareBuild = compareBuild_1; + +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)); + +var rsort_1 = rsort; +const compare$6 = compare_1; + +const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0; + +var gt_1 = gt$3; +const compare$5 = compare_1; + +const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0; + +var lt_1 = lt$2; +const compare$4 = compare_1; + +const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0; + +var neq_1 = neq$1; +const compare$3 = compare_1; + +const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0; + +var gte_1 = gte$2; +const compare$2 = compare_1; + +const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0; + +var lte_1 = lte$2; +const eq = eq_1; +const neq = neq_1; +const gt$2 = gt_1; +const gte$1 = gte_1; +const lt$1 = lt_1; +const lte$1 = lte_1; + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version; + } + + if (typeof b === 'object') { + b = b.version; + } + + return a === b; + + case '!==': + if (typeof a === 'object') { + a = a.version; + } + + if (typeof b === 'object') { + b = b.version; + } + + return a !== b; + + case '': + case '=': + case '==': + return eq(a, b, loose); + + case '!=': + return neq(a, b, loose); + + case '>': + return gt$2(a, b, loose); + + case '>=': + return gte$1(a, b, loose); + + case '<': + return lt$1(a, b, loose); + + case '<=': + return lte$1(a, b, loose); + + default: + throw new TypeError(`Invalid operator: ${op}`); + } +}; + +var cmp_1 = cmp; +const SemVer$4 = semver$2; +const parse = parse_1; +const { + re, + t +} = re$3.exports; + +const coerce = (version, options) => { + if (version instanceof SemVer$4) { + return version; + } + + if (typeof version === 'number') { + version = String(version); + } + + if (typeof version !== 'string') { + return null; + } + + options = options || {}; + let match = null; + + if (!options.rtl) { + match = version.match(re[t.COERCE]); + } else { + let next; + + while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) { + if (!match || next.index + next[0].length !== match.index + match[0].length) { + match = next; + } + + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length; + } + + re[t.COERCERTL].lastIndex = -1; + } + + if (match === null) { + return null; + } + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options); +}; + +var coerce_1 = coerce; +var iterator; +var hasRequiredIterator; + +function requireIterator() { + if (hasRequiredIterator) return iterator; + hasRequiredIterator = 1; + + iterator = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value; + } + }; + }; + + return iterator; +} + +var yallist; +var hasRequiredYallist; + +function requireYallist() { + if (hasRequiredYallist) return yallist; + hasRequiredYallist = 1; + yallist = Yallist; + Yallist.Node = Node; + Yallist.create = Yallist; + + function Yallist(list) { + var self = this; + + if (!(self instanceof Yallist)) { + self = new Yallist(); + } + + self.tail = null; + self.head = null; + self.length = 0; + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); + }); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); + } + } + + return self; + } + + Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list'); + } + + var next = node.next; + var prev = node.prev; + + if (next) { + next.prev = prev; + } + + if (prev) { + prev.next = next; + } + + if (node === this.head) { + this.head = next; + } + + if (node === this.tail) { + this.tail = prev; + } + + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; + return next; + }; + + Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return; + } + + if (node.list) { + node.list.removeNode(node); + } + + var head = this.head; + node.list = this; + node.next = head; + + if (head) { + head.prev = node; + } + + this.head = node; + + if (!this.tail) { + this.tail = node; + } + + this.length++; + }; + + Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return; + } + + if (node.list) { + node.list.removeNode(node); + } + + var tail = this.tail; + node.list = this; + node.prev = tail; + + if (tail) { + tail.next = node; + } + + this.tail = node; + + if (!this.head) { + this.head = node; + } + + this.length++; + }; + + Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]); + } + + return this.length; + }; + + Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + + return this.length; + }; + + Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined; + } + + var res = this.tail.value; + this.tail = this.tail.prev; + + if (this.tail) { + this.tail.next = null; + } else { + this.head = null; + } + + this.length--; + return res; + }; + + Yallist.prototype.shift = function () { + if (!this.head) { + return undefined; + } + + var res = this.head.value; + this.head = this.head.next; + + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + + this.length--; + return res; + }; + + Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } + }; + + Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } + }; + + Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + walker = walker.next; + } + + if (i === n && walker !== null) { + return walker.value; + } + }; + + Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + walker = walker.prev; + } + + if (i === n && walker !== null) { + return walker.value; + } + }; + + Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist(); + + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + + return res; + }; + + Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist(); + + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + + return res; + }; + + Yallist.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; + } else { + throw new TypeError('Reduce of empty list with no initial value'); + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } + + return acc; + }; + + Yallist.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value'); + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } + + return acc; + }; + + Yallist.prototype.toArray = function () { + var arr = new Array(this.length); + + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + + return arr; + }; + + Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + + return arr; + }; + + Yallist.prototype.slice = function (from, to) { + to = to || this.length; + + if (to < 0) { + to += this.length; + } + + from = from || 0; + + if (from < 0) { + from += this.length; + } + + var ret = new Yallist(); + + if (to < from || to < 0) { + return ret; + } + + if (from < 0) { + from = 0; + } + + if (to > this.length) { + to = this.length; + } + + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + + return ret; + }; + + Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length; + + if (to < 0) { + to += this.length; + } + + from = from || 0; + + if (from < 0) { + from += this.length; + } + + var ret = new Yallist(); + + if (to < from || to < 0) { + return ret; + } + + if (from < 0) { + from = 0; + } + + if (to > this.length) { + to = this.length; + } + + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + + return ret; + }; + + Yallist.prototype.splice = function (start, deleteCount, ...nodes) { + if (start > this.length) { + start = this.length - 1; + } + + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next; + } + + var ret = []; + + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value); + walker = this.removeNode(walker); + } + + if (walker === null) { + walker = this.tail; + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev; + } + + for (var i = 0; i < nodes.length; i++) { + walker = insert(this, walker, nodes[i]); + } + + return ret; + }; + + Yallist.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + + this.head = tail; + this.tail = head; + return this; + }; + + function insert(self, node, value) { + var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self); + + if (inserted.next === null) { + self.tail = inserted; + } + + if (inserted.prev === null) { + self.head = inserted; + } + + self.length++; + return inserted; + } + + function push(self, item) { + self.tail = new Node(item, self.tail, null, self); + + if (!self.head) { + self.head = self.tail; + } + + self.length++; + } + + function unshift(self, item) { + self.head = new Node(item, null, self.head, self); + + if (!self.tail) { + self.tail = self.head; + } + + self.length++; + } + + function Node(value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list); + } + + this.list = list; + this.value = value; + + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; + } + + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } + } + + try { + requireIterator()(Yallist); + } catch (er) {} + + return yallist; +} + +var lruCache; +var hasRequiredLruCache; + +function requireLruCache() { + if (hasRequiredLruCache) return lruCache; + hasRequiredLruCache = 1; + const Yallist = requireYallist(); + const MAX = Symbol('max'); + const LENGTH = Symbol('length'); + const LENGTH_CALCULATOR = Symbol('lengthCalculator'); + const ALLOW_STALE = Symbol('allowStale'); + const MAX_AGE = Symbol('maxAge'); + const DISPOSE = Symbol('dispose'); + const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet'); + const LRU_LIST = Symbol('lruList'); + const CACHE = Symbol('cache'); + const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet'); + + const naiveLength = () => 1; + + class LRUCache { + constructor(options) { + if (typeof options === 'number') options = { + max: options + }; + if (!options) options = {}; + if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number'); + this[MAX] = options.max || Infinity; + const lc = options.length || naiveLength; + this[LENGTH_CALCULATOR] = typeof lc !== 'function' ? naiveLength : lc; + this[ALLOW_STALE] = options.stale || false; + if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number'); + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false; + this.reset(); + } + + set max(mL) { + if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number'); + this[MAX] = mL || Infinity; + trim(this); + } + + get max() { + return this[MAX]; + } + + set allowStale(allowStale) { + this[ALLOW_STALE] = !!allowStale; + } + + get allowStale() { + return this[ALLOW_STALE]; + } + + set maxAge(mA) { + if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number'); + this[MAX_AGE] = mA; + trim(this); + } + + get maxAge() { + return this[MAX_AGE]; + } + + set lengthCalculator(lC) { + if (typeof lC !== 'function') lC = naiveLength; + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }); + } + + trim(this); + } + + get lengthCalculator() { + return this[LENGTH_CALCULATOR]; + } + + get length() { + return this[LENGTH]; + } + + get itemCount() { + return this[LRU_LIST].length; + } + + rforEach(fn, thisp) { + thisp = thisp || this; + + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; + } + } + + forEach(fn, thisp) { + thisp = thisp || this; + + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; + } + } + + keys() { + return this[LRU_LIST].toArray().map(k => k.key); + } + + values() { + return this[LRU_LIST].toArray().map(k => k.value); + } + + reset() { + if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)); + } + + this[CACHE] = new Map(); + this[LRU_LIST] = new Yallist(); + this[LENGTH] = 0; + } + + dump() { + return this[LRU_LIST].map(hit => isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h); + } + + dumpLru() { + return this[LRU_LIST]; + } + + set(key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; + if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number'); + const now = maxAge ? Date.now() : 0; + const len = this[LENGTH_CALCULATOR](value, key); + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false; + } + + const node = this[CACHE].get(key); + const item = node.value; + + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value); + } + + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim(this); + return true; + } + + const hit = new Entry(key, value, len, now, maxAge); + + if (hit.length > this[MAX]) { + if (this[DISPOSE]) this[DISPOSE](key, value); + return false; + } + + this[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim(this); + return true; + } + + has(key) { + if (!this[CACHE].has(key)) return false; + const hit = this[CACHE].get(key).value; + return !isStale(this, hit); + } + + get(key) { + return get(this, key, true); + } + + peek(key) { + return get(this, key, false); + } + + pop() { + const node = this[LRU_LIST].tail; + if (!node) return null; + del(this, node); + return node.value; + } + + del(key) { + del(this, this[CACHE].get(key)); + } + + load(arr) { + this.reset(); + const now = Date.now(); + + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l]; + const expiresAt = hit.e || 0; + if (expiresAt === 0) this.set(hit.k, hit.v);else { + const maxAge = expiresAt - now; + + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } + } + } + } + + prune() { + this[CACHE].forEach((value, key) => get(this, key, false)); + } + + } + + const get = (self, key, doUse) => { + const node = self[CACHE].get(key); + + if (node) { + const hit = node.value; + + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) return undefined; + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now(); + self[LRU_LIST].unshiftNode(node); + } + } + + return hit.value; + } + }; + + const isStale = (self, hit) => { + if (!hit || !hit.maxAge && !self[MAX_AGE]) return false; + const diff = Date.now() - hit.now; + return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && diff > self[MAX_AGE]; + }; + + const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { + const prev = walker.prev; + del(self, walker); + walker = prev; + } + } + }; + + const del = (self, node) => { + if (node) { + const hit = node.value; + if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value); + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } + }; + + class Entry { + constructor(key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; + } + + } + + const forEachStep = (self, fn, node, thisp) => { + let hit = node.value; + + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) hit = undefined; + } + + if (hit) fn.call(thisp, hit.value, hit.key, self); + }; + + lruCache = LRUCache; + return lruCache; +} + +var range; +var hasRequiredRange; + +function requireRange() { + if (hasRequiredRange) return range; + hasRequiredRange = 1; + + class Range { + constructor(range, options) { + options = parseOptions(options); + + if (range instanceof Range) { + if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { + return range; + } else { + return new Range(range.raw, options); + } + } + + if (range instanceof Comparator) { + this.raw = range.value; + this.set = [[range]]; + this.format(); + return this; + } + + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; + this.raw = range; + this.set = range.split('||').map(r => this.parseRange(r.trim())).filter(c => c.length); + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`); + } + + if (this.set.length > 1) { + const first = this.set[0]; + this.set = this.set.filter(c => !isNullSet(c[0])); + + if (this.set.length === 0) { + this.set = [first]; + } else if (this.set.length > 1) { + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c]; + break; + } + } + } + } + + this.format(); + } + + format() { + this.range = this.set.map(comps => { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; + } + + toString() { + return this.range; + } + + parseRange(range) { + range = range.trim(); + const memoOpts = Object.keys(this.options).join(','); + const memoKey = `parseRange:${memoOpts}:${range}`; + const cached = cache.get(memoKey); + + if (cached) { + return cached; + } + + const loose = this.options.loose; + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]; + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)); + debug('hyphen replace', range); + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range); + range = range.replace(re[t.TILDETRIM], tildeTrimReplace); + range = range.replace(re[t.CARETTRIM], caretTrimReplace); + range = range.split(/\s+/).join(' '); + let rangeList = range.split(' ').map(comp => parseComparator(comp, this.options)).join(' ').split(/\s+/).map(comp => replaceGTE0(comp, this.options)); + + if (loose) { + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options); + return !!comp.match(re[t.COMPARATORLOOSE]); + }); + } + + debug('range list', rangeList); + const rangeMap = new Map(); + const comparators = rangeList.map(comp => new Comparator(comp, this.options)); + + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp]; + } + + rangeMap.set(comp.value, comp); + } + + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete(''); + } + + const result = [...rangeMap.values()]; + cache.set(memoKey, result); + return result; + } + + intersects(range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required'); + } + + return this.set.some(thisComparators => { + return isSatisfiable(thisComparators, options) && range.set.some(rangeComparators => { + return isSatisfiable(rangeComparators, options) && thisComparators.every(thisComparator => { + return rangeComparators.every(rangeComparator => { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); + } + + test(version) { + if (!version) { + return false; + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true; + } + } + + return false; + } + + } + + range = Range; + const LRU = requireLruCache(); + const cache = new LRU({ + max: 1000 + }); + const parseOptions = parseOptions_1; + const Comparator = requireComparator(); + const debug = debug_1; + const SemVer = semver$2; + const { + re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace + } = re$3.exports; + + const isNullSet = c => c.value === '<0.0.0-0'; + + const isAny = c => c.value === ''; + + const isSatisfiable = (comparators, options) => { + let result = true; + const remainingComparators = comparators.slice(); + let testComparator = remainingComparators.pop(); + + while (result && remainingComparators.length) { + result = remainingComparators.every(otherComparator => { + return testComparator.intersects(otherComparator, options); + }); + testComparator = remainingComparators.pop(); + } + + return result; + }; + + const parseComparator = (comp, options) => { + debug('comp', comp, options); + comp = replaceCarets(comp, options); + debug('caret', comp); + comp = replaceTildes(comp, options); + debug('tildes', comp); + comp = replaceXRanges(comp, options); + debug('xrange', comp); + comp = replaceStars(comp, options); + debug('stars', comp); + return comp; + }; + + const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; + + const replaceTildes = (comp, options) => comp.trim().split(/\s+/).map(c => { + return replaceTilde(c, options); + }).join(' '); + + const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0`; + } else if (isX(p)) { + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; + } else if (pr) { + debug('replaceTilde pr', pr); + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; + } + + debug('tilde return', ret); + return ret; + }); + }; + + const replaceCarets = (comp, options) => comp.trim().split(/\s+/).map(c => { + return replaceCaret(c, options); + }).join(' '); + + const replaceCaret = (comp, options) => { + debug('caret', comp, options); + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]; + const z = options.includePrerelease ? '-0' : ''; + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr); + let ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`; + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`; + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`; + } + } else if (pr) { + debug('replaceCaret pr', pr); + + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; + } + } else { + debug('no pr'); + + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`; + } else { + ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`; + } + } else { + ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; + } + } + + debug('caret return', ret); + return ret; + }); + }; + + const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options); + return comp.split(/\s+/).map(c => { + return replaceXRange(c, options); + }).join(' '); + }; + + const replaceXRange = (comp, options) => { + comp = comp.trim(); + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + const xM = isX(M); + const xm = xM || isX(m); + const xp = xm || isX(p); + const anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } + + pr = options.includePrerelease ? '-0' : ''; + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + ret = '<0.0.0-0'; + } else { + ret = '*'; + } + } else if (gtlt && anyX) { + if (xm) { + m = 0; + } + + p = 0; + + if (gtlt === '>') { + gtlt = '>='; + + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + gtlt = '<'; + + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + if (gtlt === '<') { + pr = '-0'; + } + + ret = `${gtlt + M}.${m}.${p}${pr}`; + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`; + } else if (xp) { + ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; + } + + debug('xRange return', ret); + return ret; + }); + }; + + const replaceStars = (comp, options) => { + debug('replaceStars', comp, options); + return comp.trim().replace(re[t.STAR], ''); + }; + + const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options); + return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], ''); + }; + + const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}`; + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`; + } else if (fpr) { + from = `>=${from}`; + } else { + from = `>=${from}${incPr ? '-0' : ''}`; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0`; + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0`; + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}`; + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0`; + } else { + to = `<=${to}`; + } + + return `${from} ${to}`.trim(); + }; + + const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false; + } + } + + if (version.prerelease.length && !options.includePrerelease) { + for (let i = 0; i < set.length; i++) { + debug(set[i].semver); + + if (set[i].semver === Comparator.ANY) { + continue; + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver; + + if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { + return true; + } + } + } + + return false; + } + + return true; + }; + + return range; +} + +var comparator; +var hasRequiredComparator; + +function requireComparator() { + if (hasRequiredComparator) return comparator; + hasRequiredComparator = 1; + const ANY = Symbol('SemVer ANY'); + + class Comparator { + static get ANY() { + return ANY; + } + + constructor(comp, options) { + options = parseOptions(options); + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp; + } else { + comp = comp.value; + } + } + + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; + } + + debug('comp', this); + } + + parse(comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; + const m = comp.match(r); + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`); + } + + this.operator = m[1] !== undefined ? m[1] : ''; + + if (this.operator === '=') { + this.operator = ''; + } + + if (!m[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m[2], this.options.loose); + } + } + + toString() { + return this.value; + } + + test(version) { + debug('Comparator.test', version, this.options.loose); + + if (this.semver === ANY || version === ANY) { + return true; + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options); + } catch (er) { + return false; + } + } + + return cmp(version, this.operator, this.semver, this.options); + } + + intersects(comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required'); + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (this.operator === '') { + if (this.value === '') { + return true; + } + + return new Range(comp.value, options).test(this.value); + } else if (comp.operator === '') { + if (comp.value === '') { + return true; + } + + return new Range(this.value, options).test(comp.semver); + } + + const sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>'); + const sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<'); + const sameSemVer = this.semver.version === comp.semver.version; + const differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<='); + const oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<'); + const oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>'); + return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; + } + + } + + comparator = Comparator; + const parseOptions = parseOptions_1; + const { + re, + t + } = re$3.exports; + const cmp = cmp_1; + const debug = debug_1; + const SemVer = semver$2; + const Range = requireRange(); + return comparator; +} + +const Range$8 = requireRange(); + +const satisfies$3 = (version, range, options) => { + try { + range = new Range$8(range, options); + } catch (er) { + return false; + } + + return range.test(version); +}; + +var satisfies_1 = satisfies$3; +const Range$7 = requireRange(); + +const toComparators = (range, options) => new Range$7(range, options).set.map(comp => comp.map(c => c.value).join(' ').trim().split(' ')); + +var toComparators_1 = toComparators; +const SemVer$3 = semver$2; +const Range$6 = requireRange(); + +const maxSatisfying = (versions, range, options) => { + let max = null; + let maxSV = null; + let rangeObj = null; + + try { + rangeObj = new Range$6(range, options); + } catch (er) { + return null; + } + + versions.forEach(v => { + if (rangeObj.test(v)) { + if (!max || maxSV.compare(v) === -1) { + max = v; + maxSV = new SemVer$3(max, options); + } + } + }); + return max; +}; + +var maxSatisfying_1 = maxSatisfying; +const SemVer$2 = semver$2; +const Range$5 = requireRange(); + +const minSatisfying = (versions, range, options) => { + let min = null; + let minSV = null; + let rangeObj = null; + + try { + rangeObj = new Range$5(range, options); + } catch (er) { + return null; + } + + versions.forEach(v => { + if (rangeObj.test(v)) { + if (!min || minSV.compare(v) === 1) { + min = v; + minSV = new SemVer$2(min, options); + } + } + }); + return min; +}; + +var minSatisfying_1 = minSatisfying; +const SemVer$1 = semver$2; +const Range$4 = requireRange(); +const gt$1 = gt_1; + +const minVersion = (range, loose) => { + range = new Range$4(range, loose); + let minver = new SemVer$1('0.0.0'); + + if (range.test(minver)) { + return minver; + } + + minver = new SemVer$1('0.0.0-0'); + + if (range.test(minver)) { + return minver; + } + + minver = null; + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + let setMin = null; + comparators.forEach(comparator => { + const compver = new SemVer$1(comparator.semver.version); + + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + + compver.raw = compver.format(); + + case '': + case '>=': + if (!setMin || gt$1(compver, setMin)) { + setMin = compver; + } + + break; + + case '<': + case '<=': + break; + + default: + throw new Error(`Unexpected operation: ${comparator.operator}`); + } + }); + + if (setMin && (!minver || gt$1(minver, setMin))) { + minver = setMin; + } + } + + if (minver && range.test(minver)) { + return minver; + } + + return null; +}; + +var minVersion_1 = minVersion; +const Range$3 = requireRange(); + +const validRange = (range, options) => { + try { + return new Range$3(range, options).range || '*'; + } catch (er) { + return null; + } +}; + +var valid = validRange; +const SemVer = semver$2; +const Comparator$1 = requireComparator(); +const { + ANY: ANY$1 +} = Comparator$1; +const Range$2 = requireRange(); +const satisfies$2 = satisfies_1; +const gt = gt_1; +const lt = lt_1; +const lte = lte_1; +const gte = gte_1; + +const outside$2 = (version, range, hilo, options) => { + version = new SemVer(version, options); + range = new Range$2(range, options); + let gtfn, ltefn, ltfn, comp, ecomp; + + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } + + if (satisfies$2(version, range, options)) { + return false; + } + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i]; + let high = null; + let low = null; + comparators.forEach(comparator => { + if (comparator.semver === ANY$1) { + comparator = new Comparator$1('>=0.0.0'); + } + + high = high || comparator; + low = low || comparator; + + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); + + if (high.operator === comp || high.operator === ecomp) { + return false; + } + + if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + + return true; +}; + +var outside_1 = outside$2; +const outside$1 = outside_1; + +const gtr = (version, range, options) => outside$1(version, range, '>', options); + +var gtr_1 = gtr; +const outside = outside_1; + +const ltr = (version, range, options) => outside(version, range, '<', options); + +var ltr_1 = ltr; +const Range$1 = requireRange(); + +const intersects = (r1, r2, options) => { + r1 = new Range$1(r1, options); + r2 = new Range$1(r2, options); + return r1.intersects(r2); +}; + +var intersects_1 = intersects; +const satisfies$1 = satisfies_1; +const compare$1 = compare_1; + +var simplify = (versions, range, options) => { + const set = []; + let first = null; + let prev = null; + const v = versions.sort((a, b) => compare$1(a, b, options)); + + for (const version of v) { + const included = satisfies$1(version, range, options); + + if (included) { + prev = version; + + if (!first) { + first = version; + } + } else { + if (prev) { + set.push([first, prev]); + } + + prev = null; + first = null; + } + } + + if (first) { + set.push([first, null]); + } + + const ranges = []; + + for (const [min, max] of set) { + if (min === max) { + ranges.push(min); + } else if (!max && min === v[0]) { + ranges.push('*'); + } else if (!max) { + ranges.push(`>=${min}`); + } else if (min === v[0]) { + ranges.push(`<=${max}`); + } else { + ranges.push(`${min} - ${max}`); + } + } + + const simplified = ranges.join(' || '); + const original = typeof range.raw === 'string' ? range.raw : String(range); + return simplified.length < original.length ? simplified : range; +}; + +const Range = requireRange(); +const Comparator = requireComparator(); +const { + ANY +} = Comparator; +const satisfies = satisfies_1; +const compare = compare_1; + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true; + } + + sub = new Range(sub, options); + dom = new Range(dom, options); + let sawNonNull = false; + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options); + sawNonNull = sawNonNull || isSub !== null; + + if (isSub) { + continue OUTER; + } + } + + if (sawNonNull) { + return false; + } + } + + return true; +}; + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true; + } + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true; + } else if (options.includePrerelease) { + sub = [new Comparator('>=0.0.0-0')]; + } else { + sub = [new Comparator('>=0.0.0')]; + } + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true; + } else { + dom = [new Comparator('>=0.0.0')]; + } + } + + const eqSet = new Set(); + let gt, lt; + + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options); + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options); + } else { + eqSet.add(c.semver); + } + } + + if (eqSet.size > 1) { + return null; + } + + let gtltComp; + + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options); + + if (gtltComp > 0) { + return null; + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null; + } + } + + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null; + } + + if (lt && !satisfies(eq, String(lt), options)) { + return null; + } + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false; + } + } + + return true; + } + + let higher, lower; + let hasDomLT, hasDomGT; + let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false; + let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; + + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false; + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='; + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='; + + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false; + } + } + + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options); + + if (higher === c && higher !== gt) { + return false; + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false; + } + } + + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false; + } + } + + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options); + + if (lower === c && lower !== lt) { + return false; + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false; + } + } + + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false; + } + } + + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false; + } + + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false; + } + + if (needDomGTPre || needDomLTPre) { + return false; + } + + return true; +}; + +const higherGT = (a, b, options) => { + if (!a) { + return b; + } + + const comp = compare(a.semver, b.semver, options); + return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a; +}; + +const lowerLT = (a, b, options) => { + if (!a) { + return b; + } + + const comp = compare(a.semver, b.semver, options); + return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a; +}; + +var subset_1 = subset; +const internalRe = re$3.exports; +var semver$1 = { + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + SemVer: semver$2, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, + parse: parse_1, + valid: valid_1, + clean: clean_1, + inc: inc_1, + diff: diff_1, + major: major_1, + minor: minor_1, + patch: patch_1, + prerelease: prerelease_1, + compare: compare_1, + rcompare: rcompare_1, + compareLoose: compareLoose_1, + compareBuild: compareBuild_1, + sort: sort_1, + rsort: rsort_1, + gt: gt_1, + lt: lt_1, + eq: eq_1, + neq: neq_1, + gte: gte_1, + lte: lte_1, + cmp: cmp_1, + coerce: coerce_1, + Comparator: requireComparator(), + Range: requireRange(), + satisfies: satisfies_1, + toComparators: toComparators_1, + maxSatisfying: maxSatisfying_1, + minSatisfying: minSatisfying_1, + minVersion: minVersion_1, + validRange: valid, + outside: outside_1, + gtr: gtr_1, + ltr: ltr_1, + intersects: intersects_1, + simplifyRange: simplify, + subset: subset_1 +}; +var semver = semver$1; + +var builtins = function ({ + version = process.version, + experimental = false +} = {}) { + var coreModules = ['assert', 'buffer', 'child_process', 'cluster', 'console', 'constants', 'crypto', 'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'https', 'module', 'net', 'os', 'path', 'punycode', 'querystring', 'readline', 'repl', 'stream', 'string_decoder', 'sys', 'timers', 'tls', 'tty', 'url', 'util', 'vm', 'zlib']; + if (semver.lt(version, '6.0.0')) coreModules.push('freelist'); + if (semver.gte(version, '1.0.0')) coreModules.push('v8'); + if (semver.gte(version, '1.1.0')) coreModules.push('process'); + if (semver.gte(version, '8.0.0')) coreModules.push('inspector'); + if (semver.gte(version, '8.1.0')) coreModules.push('async_hooks'); + if (semver.gte(version, '8.4.0')) coreModules.push('http2'); + if (semver.gte(version, '8.5.0')) coreModules.push('perf_hooks'); + if (semver.gte(version, '10.0.0')) coreModules.push('trace_events'); + + if (semver.gte(version, '10.5.0') && (experimental || semver.gte(version, '12.0.0'))) { + coreModules.push('worker_threads'); + } + + if (semver.gte(version, '12.16.0') && experimental) { + coreModules.push('wasi'); + } + + return coreModules; +}; + +const reader = { + read +}; + +function read(jsonPath) { + return find(_path().dirname(jsonPath)); +} + +function find(dir) { + try { + const string = _fs().default.readFileSync(_path().toNamespacedPath(_path().join(dir, 'package.json')), 'utf8'); + + return { + string + }; + } catch (error) { + if (error.code === 'ENOENT') { + const parent = _path().dirname(dir); + + if (dir !== parent) return find(parent); + return { + string: undefined + }; + } + + throw error; + } +} + +const isWindows = process.platform === 'win32'; +const own$1 = {}.hasOwnProperty; +const codes = {}; +const messages = new Map(); +const nodeInternalPrefix = '__node_internal_'; +let userStackTraceLimit; +codes.ERR_INVALID_MODULE_SPECIFIER = createError('ERR_INVALID_MODULE_SPECIFIER', (request, reason, base = undefined) => { + return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ''}`; +}, TypeError); +codes.ERR_INVALID_PACKAGE_CONFIG = createError('ERR_INVALID_PACKAGE_CONFIG', (path, base, message) => { + return `Invalid package config ${path}${base ? ` while importing ${base}` : ''}${message ? `. ${message}` : ''}`; +}, Error); +codes.ERR_INVALID_PACKAGE_TARGET = createError('ERR_INVALID_PACKAGE_TARGET', (pkgPath, key, target, isImport = false, base = undefined) => { + const relError = typeof target === 'string' && !isImport && target.length > 0 && !target.startsWith('./'); + + if (key === '.') { + _assert()(isImport === false); + + return `Invalid "exports" main target ${JSON.stringify(target)} defined ` + `in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ''}${relError ? '; targets must start with "./"' : ''}`; + } + + return `Invalid "${isImport ? 'imports' : 'exports'}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ''}${relError ? '; targets must start with "./"' : ''}`; +}, Error); +codes.ERR_MODULE_NOT_FOUND = createError('ERR_MODULE_NOT_FOUND', (path, base, type = 'package') => { + return `Cannot find ${type} '${path}' imported from ${base}`; +}, Error); +codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError('ERR_PACKAGE_IMPORT_NOT_DEFINED', (specifier, packagePath, base) => { + return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ''} imported from ${base}`; +}, TypeError); +codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError('ERR_PACKAGE_PATH_NOT_EXPORTED', (pkgPath, subpath, base = undefined) => { + if (subpath === '.') return `No "exports" main defined in ${pkgPath}package.json${base ? ` imported from ${base}` : ''}`; + return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${base ? ` imported from ${base}` : ''}`; +}, Error); +codes.ERR_UNSUPPORTED_DIR_IMPORT = createError('ERR_UNSUPPORTED_DIR_IMPORT', "Directory import '%s' is not supported " + 'resolving ES modules imported from %s', Error); +codes.ERR_UNKNOWN_FILE_EXTENSION = createError('ERR_UNKNOWN_FILE_EXTENSION', 'Unknown file extension "%s" for %s', TypeError); +codes.ERR_INVALID_ARG_VALUE = createError('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => { + let inspected = (0, _util().inspect)(value); + + if (inspected.length > 128) { + inspected = `${inspected.slice(0, 128)}...`; + } + + const type = name.includes('.') ? 'property' : 'argument'; + return `The ${type} '${name}' ${reason}. Received ${inspected}`; +}, TypeError); +codes.ERR_UNSUPPORTED_ESM_URL_SCHEME = createError('ERR_UNSUPPORTED_ESM_URL_SCHEME', url => { + let message = 'Only file and data URLs are supported by the default ESM loader'; + + if (isWindows && url.protocol.length === 2) { + message += '. On Windows, absolute paths must be valid file:// URLs'; + } + + message += `. Received protocol '${url.protocol}'`; + return message; +}, Error); + +function createError(sym, value, def) { + messages.set(sym, value); + return makeNodeErrorWithCode(def, sym); +} + +function makeNodeErrorWithCode(Base, key) { + return NodeError; + + function NodeError(...args) { + const limit = Error.stackTraceLimit; + if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0; + const error = new Base(); + if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit; + const message = getMessage(key, args, error); + Object.defineProperty(error, 'message', { + value: message, + enumerable: false, + writable: true, + configurable: true + }); + Object.defineProperty(error, 'toString', { + value() { + return `${this.name} [${key}]: ${this.message}`; + }, + + enumerable: false, + writable: true, + configurable: true + }); + addCodeToName(error, Base.name, key); + error.code = key; + return error; + } +} + +const addCodeToName = hideStackFrames(function (error, name, code) { + error = captureLargerStackTrace(error); + error.name = `${name} [${code}]`; + error.stack; + + if (name === 'SystemError') { + Object.defineProperty(error, 'name', { + value: name, + enumerable: false, + writable: true, + configurable: true + }); + } else { + delete error.name; + } +}); + +function isErrorStackTraceLimitWritable() { + const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit'); + + if (desc === undefined) { + return Object.isExtensible(Error); + } + + return own$1.call(desc, 'writable') ? desc.writable : desc.set !== undefined; +} + +function hideStackFrames(fn) { + const hidden = nodeInternalPrefix + fn.name; + Object.defineProperty(fn, 'name', { + value: hidden + }); + return fn; +} + +const captureLargerStackTrace = hideStackFrames(function (error) { + const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable(); + + if (stackTraceLimitIsWritable) { + userStackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = Number.POSITIVE_INFINITY; + } + + Error.captureStackTrace(error); + if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit; + return error; +}); + +function getMessage(key, args, self) { + const message = messages.get(key); + + if (typeof message === 'function') { + _assert()(message.length <= args.length, `Code: ${key}; The provided arguments length (${args.length}) does not ` + `match the required ones (${message.length}).`); + + return Reflect.apply(message, self, args); + } + + const expectedLength = (message.match(/%[dfijoOs]/g) || []).length; + + _assert()(expectedLength === args.length, `Code: ${key}; The provided arguments length (${args.length}) does not ` + `match the required ones (${expectedLength}).`); + + if (args.length === 0) return message; + args.unshift(message); + return Reflect.apply(_util().format, null, args); +} + +const { + ERR_UNKNOWN_FILE_EXTENSION +} = codes; +const extensionFormatMap = { + __proto__: null, + '.cjs': 'commonjs', + '.js': 'module', + '.mjs': 'module' +}; + +function defaultGetFormat(url) { + if (url.startsWith('node:')) { + return { + format: 'builtin' + }; + } + + const parsed = new (_url().URL)(url); + + if (parsed.protocol === 'data:') { + const { + 1: mime + } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(parsed.pathname) || [null, null]; + const format = mime === 'text/javascript' ? 'module' : null; + return { + format + }; + } + + if (parsed.protocol === 'file:') { + const ext = _path().extname(parsed.pathname); + + let format; + + if (ext === '.js') { + format = getPackageType(parsed.href) === 'module' ? 'module' : 'commonjs'; + } else { + format = extensionFormatMap[ext]; + } + + if (!format) { + throw new ERR_UNKNOWN_FILE_EXTENSION(ext, (0, _url().fileURLToPath)(url)); + } + + return { + format: format || null + }; + } + + return { + format: null + }; +} + +const listOfBuiltins = builtins(); +const { + ERR_INVALID_MODULE_SPECIFIER, + ERR_INVALID_PACKAGE_CONFIG, + ERR_INVALID_PACKAGE_TARGET, + ERR_MODULE_NOT_FOUND, + ERR_PACKAGE_IMPORT_NOT_DEFINED, + ERR_PACKAGE_PATH_NOT_EXPORTED, + ERR_UNSUPPORTED_DIR_IMPORT, + ERR_UNSUPPORTED_ESM_URL_SCHEME, + ERR_INVALID_ARG_VALUE +} = codes; +const own = {}.hasOwnProperty; +const DEFAULT_CONDITIONS = Object.freeze(['node', 'import']); +const DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS); +const invalidSegmentRegEx = /(^|\\|\/)(\.\.?|node_modules)(\\|\/|$)/; +const patternRegEx = /\*/g; +const encodedSepRegEx = /%2f|%2c/i; +const emittedPackageWarnings = new Set(); +const packageJsonCache = new Map(); + +function emitFolderMapDeprecation(match, pjsonUrl, isExports, base) { + const pjsonPath = (0, _url().fileURLToPath)(pjsonUrl); + if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return; + emittedPackageWarnings.add(pjsonPath + '|' + match); + process.emitWarning(`Use of deprecated folder mapping "${match}" in the ${isExports ? '"exports"' : '"imports"'} field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, _url().fileURLToPath)(base)}` : ''}.\n` + `Update this package.json to use a subpath pattern like "${match}*".`, 'DeprecationWarning', 'DEP0148'); +} + +function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) { + const { + format + } = defaultGetFormat(url.href); + if (format !== 'module') return; + const path = (0, _url().fileURLToPath)(url.href); + const pkgPath = (0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)); + const basePath = (0, _url().fileURLToPath)(base); + if (main) process.emitWarning(`Package ${pkgPath} has a "main" field set to ${JSON.stringify(main)}, ` + `excluding the full filename and extension to the resolved file at "${path.slice(pkgPath.length)}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is` + 'deprecated for ES modules.', 'DeprecationWarning', 'DEP0151');else process.emitWarning(`No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${path.slice(pkgPath.length)}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`, 'DeprecationWarning', 'DEP0151'); +} + +function getConditionsSet(conditions) { + if (conditions !== undefined && conditions !== DEFAULT_CONDITIONS) { + if (!Array.isArray(conditions)) { + throw new ERR_INVALID_ARG_VALUE('conditions', conditions, 'expected an array'); + } + + return new Set(conditions); + } + + return DEFAULT_CONDITIONS_SET; +} + +function tryStatSync(path) { + try { + return (0, _fs().statSync)(path); + } catch (_unused) { + return new (_fs().Stats)(); + } +} + +function getPackageConfig(path, specifier, base) { + const existing = packageJsonCache.get(path); + + if (existing !== undefined) { + return existing; + } + + const source = reader.read(path).string; + + if (source === undefined) { + const packageConfig = { + pjsonPath: path, + exists: false, + main: undefined, + name: undefined, + type: 'none', + exports: undefined, + imports: undefined + }; + packageJsonCache.set(path, packageConfig); + return packageConfig; + } + + let packageJson; + + try { + packageJson = JSON.parse(source); + } catch (error) { + throw new ERR_INVALID_PACKAGE_CONFIG(path, (base ? `"${specifier}" from ` : '') + (0, _url().fileURLToPath)(base || specifier), error.message); + } + + const { + exports, + imports, + main, + name, + type + } = packageJson; + const packageConfig = { + pjsonPath: path, + exists: true, + main: typeof main === 'string' ? main : undefined, + name: typeof name === 'string' ? name : undefined, + type: type === 'module' || type === 'commonjs' ? type : 'none', + exports, + imports: imports && typeof imports === 'object' ? imports : undefined + }; + packageJsonCache.set(path, packageConfig); + return packageConfig; +} + +function getPackageScopeConfig(resolved) { + let packageJsonUrl = new (_url().URL)('./package.json', resolved); + + while (true) { + const packageJsonPath = packageJsonUrl.pathname; + if (packageJsonPath.endsWith('node_modules/package.json')) break; + const packageConfig = getPackageConfig((0, _url().fileURLToPath)(packageJsonUrl), resolved); + if (packageConfig.exists) return packageConfig; + const lastPackageJsonUrl = packageJsonUrl; + packageJsonUrl = new (_url().URL)('../package.json', packageJsonUrl); + if (packageJsonUrl.pathname === lastPackageJsonUrl.pathname) break; + } + + const packageJsonPath = (0, _url().fileURLToPath)(packageJsonUrl); + const packageConfig = { + pjsonPath: packageJsonPath, + exists: false, + main: undefined, + name: undefined, + type: 'none', + exports: undefined, + imports: undefined + }; + packageJsonCache.set(packageJsonPath, packageConfig); + return packageConfig; +} + +function fileExists(url) { + return tryStatSync((0, _url().fileURLToPath)(url)).isFile(); +} + +function legacyMainResolve(packageJsonUrl, packageConfig, base) { + let guess; + + if (packageConfig.main !== undefined) { + guess = new (_url().URL)(`./${packageConfig.main}`, packageJsonUrl); + if (fileExists(guess)) return guess; + const tries = [`./${packageConfig.main}.js`, `./${packageConfig.main}.json`, `./${packageConfig.main}.node`, `./${packageConfig.main}/index.js`, `./${packageConfig.main}/index.json`, `./${packageConfig.main}/index.node`]; + let i = -1; + + while (++i < tries.length) { + guess = new (_url().URL)(tries[i], packageJsonUrl); + if (fileExists(guess)) break; + guess = undefined; + } + + if (guess) { + emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); + return guess; + } + } + + const tries = ['./index.js', './index.json', './index.node']; + let i = -1; + + while (++i < tries.length) { + guess = new (_url().URL)(tries[i], packageJsonUrl); + if (fileExists(guess)) break; + guess = undefined; + } + + if (guess) { + emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main); + return guess; + } + + throw new ERR_MODULE_NOT_FOUND((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), (0, _url().fileURLToPath)(base)); +} + +function finalizeResolution(resolved, base) { + if (encodedSepRegEx.test(resolved.pathname)) throw new ERR_INVALID_MODULE_SPECIFIER(resolved.pathname, 'must not include encoded "/" or "\\" characters', (0, _url().fileURLToPath)(base)); + const path = (0, _url().fileURLToPath)(resolved); + const stats = tryStatSync(path.endsWith('/') ? path.slice(-1) : path); + + if (stats.isDirectory()) { + const error = new ERR_UNSUPPORTED_DIR_IMPORT(path, (0, _url().fileURLToPath)(base)); + error.url = String(resolved); + throw error; + } + + if (!stats.isFile()) { + throw new ERR_MODULE_NOT_FOUND(path || resolved.pathname, base && (0, _url().fileURLToPath)(base), 'module'); + } + + return resolved; +} + +function throwImportNotDefined(specifier, packageJsonUrl, base) { + throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJsonUrl && (0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), (0, _url().fileURLToPath)(base)); +} + +function throwExportsNotFound(subpath, packageJsonUrl, base) { + throw new ERR_PACKAGE_PATH_NOT_EXPORTED((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), subpath, base && (0, _url().fileURLToPath)(base)); +} + +function throwInvalidSubpath(subpath, packageJsonUrl, internal, base) { + const reason = `request is not a valid subpath for the "${internal ? 'imports' : 'exports'}" resolution of ${(0, _url().fileURLToPath)(packageJsonUrl)}`; + throw new ERR_INVALID_MODULE_SPECIFIER(subpath, reason, base && (0, _url().fileURLToPath)(base)); +} + +function throwInvalidPackageTarget(subpath, target, packageJsonUrl, internal, base) { + target = typeof target === 'object' && target !== null ? JSON.stringify(target, null, '') : `${target}`; + throw new ERR_INVALID_PACKAGE_TARGET((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), subpath, target, internal, base && (0, _url().fileURLToPath)(base)); +} + +function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, conditions) { + if (subpath !== '' && !pattern && target[target.length - 1] !== '/') throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base); + + if (!target.startsWith('./')) { + if (internal && !target.startsWith('../') && !target.startsWith('/')) { + let isURL = false; + + try { + new (_url().URL)(target); + isURL = true; + } catch (_unused2) {} + + if (!isURL) { + const exportTarget = pattern ? target.replace(patternRegEx, subpath) : target + subpath; + return packageResolve(exportTarget, packageJsonUrl, conditions); + } + } + + throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base); + } + + if (invalidSegmentRegEx.test(target.slice(2))) throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base); + const resolved = new (_url().URL)(target, packageJsonUrl); + const resolvedPath = resolved.pathname; + const packagePath = new (_url().URL)('.', packageJsonUrl).pathname; + if (!resolvedPath.startsWith(packagePath)) throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base); + if (subpath === '') return resolved; + if (invalidSegmentRegEx.test(subpath)) throwInvalidSubpath(match + subpath, packageJsonUrl, internal, base); + if (pattern) return new (_url().URL)(resolved.href.replace(patternRegEx, subpath)); + return new (_url().URL)(subpath, resolved); +} + +function isArrayIndex(key) { + const keyNumber = Number(key); + if (`${keyNumber}` !== key) return false; + return keyNumber >= 0 && keyNumber < 0xffffffff; +} + +function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, conditions) { + if (typeof target === 'string') { + return resolvePackageTargetString(target, subpath, packageSubpath, packageJsonUrl, base, pattern, internal, conditions); + } + + if (Array.isArray(target)) { + const targetList = target; + if (targetList.length === 0) return null; + let lastException; + let i = -1; + + while (++i < targetList.length) { + const targetItem = targetList[i]; + let resolved; + + try { + resolved = resolvePackageTarget(packageJsonUrl, targetItem, subpath, packageSubpath, base, pattern, internal, conditions); + } catch (error) { + lastException = error; + if (error.code === 'ERR_INVALID_PACKAGE_TARGET') continue; + throw error; + } + + if (resolved === undefined) continue; + + if (resolved === null) { + lastException = null; + continue; + } + + return resolved; + } + + if (lastException === undefined || lastException === null) { + return lastException; + } + + throw lastException; + } + + if (typeof target === 'object' && target !== null) { + const keys = Object.getOwnPropertyNames(target); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + + if (isArrayIndex(key)) { + throw new ERR_INVALID_PACKAGE_CONFIG((0, _url().fileURLToPath)(packageJsonUrl), base, '"exports" cannot contain numeric property keys.'); + } + } + + i = -1; + + while (++i < keys.length) { + const key = keys[i]; + + if (key === 'default' || conditions && conditions.has(key)) { + const conditionalTarget = target[key]; + const resolved = resolvePackageTarget(packageJsonUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, conditions); + if (resolved === undefined) continue; + return resolved; + } + } + + return undefined; + } + + if (target === null) { + return null; + } + + throwInvalidPackageTarget(packageSubpath, target, packageJsonUrl, internal, base); +} + +function isConditionalExportsMainSugar(exports, packageJsonUrl, base) { + if (typeof exports === 'string' || Array.isArray(exports)) return true; + if (typeof exports !== 'object' || exports === null) return false; + const keys = Object.getOwnPropertyNames(exports); + let isConditionalSugar = false; + let i = 0; + let j = -1; + + while (++j < keys.length) { + const key = keys[j]; + const curIsConditionalSugar = key === '' || key[0] !== '.'; + + if (i++ === 0) { + isConditionalSugar = curIsConditionalSugar; + } else if (isConditionalSugar !== curIsConditionalSugar) { + throw new ERR_INVALID_PACKAGE_CONFIG((0, _url().fileURLToPath)(packageJsonUrl), base, '"exports" cannot contain some keys starting with \'.\' and some not.' + ' The exports object must either be an object of package subpath keys' + ' or an object of main entry condition name keys only.'); + } + } + + return isConditionalSugar; +} + +function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) { + let exports = packageConfig.exports; + if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) exports = { + '.': exports + }; + + if (own.call(exports, packageSubpath)) { + const target = exports[packageSubpath]; + const resolved = resolvePackageTarget(packageJsonUrl, target, '', packageSubpath, base, false, false, conditions); + if (resolved === null || resolved === undefined) throwExportsNotFound(packageSubpath, packageJsonUrl, base); + return { + resolved, + exact: true + }; + } + + let bestMatch = ''; + const keys = Object.getOwnPropertyNames(exports); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + + if (key[key.length - 1] === '*' && packageSubpath.startsWith(key.slice(0, -1)) && packageSubpath.length >= key.length && key.length > bestMatch.length) { + bestMatch = key; + } else if (key[key.length - 1] === '/' && packageSubpath.startsWith(key) && key.length > bestMatch.length) { + bestMatch = key; + } + } + + if (bestMatch) { + const target = exports[bestMatch]; + const pattern = bestMatch[bestMatch.length - 1] === '*'; + const subpath = packageSubpath.slice(bestMatch.length - (pattern ? 1 : 0)); + const resolved = resolvePackageTarget(packageJsonUrl, target, subpath, bestMatch, base, pattern, false, conditions); + if (resolved === null || resolved === undefined) throwExportsNotFound(packageSubpath, packageJsonUrl, base); + if (!pattern) emitFolderMapDeprecation(bestMatch, packageJsonUrl, true, base); + return { + resolved, + exact: pattern + }; + } + + throwExportsNotFound(packageSubpath, packageJsonUrl, base); +} + +function packageImportsResolve(name, base, conditions) { + if (name === '#' || name.startsWith('#/')) { + const reason = 'is not a valid internal imports specifier name'; + throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, (0, _url().fileURLToPath)(base)); + } + + let packageJsonUrl; + const packageConfig = getPackageScopeConfig(base); + + if (packageConfig.exists) { + packageJsonUrl = (0, _url().pathToFileURL)(packageConfig.pjsonPath); + const imports = packageConfig.imports; + + if (imports) { + if (own.call(imports, name)) { + const resolved = resolvePackageTarget(packageJsonUrl, imports[name], '', name, base, false, true, conditions); + if (resolved !== null) return { + resolved, + exact: true + }; + } else { + let bestMatch = ''; + const keys = Object.getOwnPropertyNames(imports); + let i = -1; + + while (++i < keys.length) { + const key = keys[i]; + + if (key[key.length - 1] === '*' && name.startsWith(key.slice(0, -1)) && name.length >= key.length && key.length > bestMatch.length) { + bestMatch = key; + } else if (key[key.length - 1] === '/' && name.startsWith(key) && key.length > bestMatch.length) { + bestMatch = key; + } + } + + if (bestMatch) { + const target = imports[bestMatch]; + const pattern = bestMatch[bestMatch.length - 1] === '*'; + const subpath = name.slice(bestMatch.length - (pattern ? 1 : 0)); + const resolved = resolvePackageTarget(packageJsonUrl, target, subpath, bestMatch, base, pattern, true, conditions); + + if (resolved !== null) { + if (!pattern) emitFolderMapDeprecation(bestMatch, packageJsonUrl, false, base); + return { + resolved, + exact: pattern + }; + } + } + } + } + } + + throwImportNotDefined(name, packageJsonUrl, base); +} + +function getPackageType(url) { + const packageConfig = getPackageScopeConfig(url); + return packageConfig.type; +} + +function parsePackageName(specifier, base) { + let separatorIndex = specifier.indexOf('/'); + let validPackageName = true; + let isScoped = false; + + if (specifier[0] === '@') { + isScoped = true; + + if (separatorIndex === -1 || specifier.length === 0) { + validPackageName = false; + } else { + separatorIndex = specifier.indexOf('/', separatorIndex + 1); + } + } + + const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex); + let i = -1; + + while (++i < packageName.length) { + if (packageName[i] === '%' || packageName[i] === '\\') { + validPackageName = false; + break; + } + } + + if (!validPackageName) { + throw new ERR_INVALID_MODULE_SPECIFIER(specifier, 'is not a valid package name', (0, _url().fileURLToPath)(base)); + } + + const packageSubpath = '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex)); + return { + packageName, + packageSubpath, + isScoped + }; +} + +function packageResolve(specifier, base, conditions) { + const { + packageName, + packageSubpath, + isScoped + } = parsePackageName(specifier, base); + const packageConfig = getPackageScopeConfig(base); + + if (packageConfig.exists) { + const packageJsonUrl = (0, _url().pathToFileURL)(packageConfig.pjsonPath); + + if (packageConfig.name === packageName && packageConfig.exports !== undefined && packageConfig.exports !== null) { + return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions).resolved; + } + } + + let packageJsonUrl = new (_url().URL)('./node_modules/' + packageName + '/package.json', base); + let packageJsonPath = (0, _url().fileURLToPath)(packageJsonUrl); + let lastPath; + + do { + const stat = tryStatSync(packageJsonPath.slice(0, -13)); + + if (!stat.isDirectory()) { + lastPath = packageJsonPath; + packageJsonUrl = new (_url().URL)((isScoped ? '../../../../node_modules/' : '../../../node_modules/') + packageName + '/package.json', packageJsonUrl); + packageJsonPath = (0, _url().fileURLToPath)(packageJsonUrl); + continue; + } + + const packageConfig = getPackageConfig(packageJsonPath, specifier, base); + if (packageConfig.exports !== undefined && packageConfig.exports !== null) return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions).resolved; + if (packageSubpath === '.') return legacyMainResolve(packageJsonUrl, packageConfig, base); + return new (_url().URL)(packageSubpath, packageJsonUrl); + } while (packageJsonPath.length !== lastPath.length); + + throw new ERR_MODULE_NOT_FOUND(packageName, (0, _url().fileURLToPath)(base)); +} + +function isRelativeSpecifier(specifier) { + if (specifier[0] === '.') { + if (specifier.length === 1 || specifier[1] === '/') return true; + + if (specifier[1] === '.' && (specifier.length === 2 || specifier[2] === '/')) { + return true; + } + } + + return false; +} + +function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) { + if (specifier === '') return false; + if (specifier[0] === '/') return true; + return isRelativeSpecifier(specifier); +} + +function moduleResolve(specifier, base, conditions) { + let resolved; + + if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) { + resolved = new (_url().URL)(specifier, base); + } else if (specifier[0] === '#') { + ({ + resolved + } = packageImportsResolve(specifier, base, conditions)); + } else { + try { + resolved = new (_url().URL)(specifier); + } catch (_unused3) { + resolved = packageResolve(specifier, base, conditions); + } + } + + return finalizeResolution(resolved, base); +} + +function defaultResolve(specifier, context = {}) { + const { + parentURL + } = context; + let parsed; + + try { + parsed = new (_url().URL)(specifier); + + if (parsed.protocol === 'data:') { + return { + url: specifier + }; + } + } catch (_unused4) {} + + if (parsed && parsed.protocol === 'node:') return { + url: specifier + }; + if (parsed && parsed.protocol !== 'file:' && parsed.protocol !== 'data:') throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(parsed); + + if (listOfBuiltins.includes(specifier)) { + return { + url: 'node:' + specifier + }; + } + + if (parentURL.startsWith('data:')) { + new (_url().URL)(specifier, parentURL); + } + + const conditions = getConditionsSet(context.conditions); + let url = moduleResolve(specifier, new (_url().URL)(parentURL), conditions); + const urlPath = (0, _url().fileURLToPath)(url); + const real = (0, _fs().realpathSync)(urlPath); + const old = url; + url = (0, _url().pathToFileURL)(real + (urlPath.endsWith(_path().sep) ? '/' : '')); + url.search = old.search; + url.hash = old.hash; + return { + url: `${url}` + }; +} + +function resolve(_x, _x2) { + return _resolve.apply(this, arguments); +} + +function _resolve() { + _resolve = _asyncToGenerator(function* (specifier, parent) { + if (!parent) { + throw new Error('Please pass `parent`: `import-meta-resolve` cannot ponyfill that'); + } + + try { + return defaultResolve(specifier, { + parentURL: parent + }).url; + } catch (error) { + return error.code === 'ERR_UNSUPPORTED_DIR_IMPORT' ? error.url : Promise.reject(error); + } + }); + return _resolve.apply(this, arguments); +} + +0 && 0; + +//# sourceMappingURL=import-meta-resolve.js.map diff --git a/node_modules/@babel/core/lib/vendor/import-meta-resolve.js.map b/node_modules/@babel/core/lib/vendor/import-meta-resolve.js.map new file mode 100644 index 0000000..d7389f3 --- /dev/null +++ b/node_modules/@babel/core/lib/vendor/import-meta-resolve.js.map @@ -0,0 +1 @@ +{"version":3,"names":["re$3","exports","SEMVER_SPEC_VERSION","MAX_LENGTH$2","MAX_SAFE_INTEGER$1","Number","MAX_SAFE_INTEGER","MAX_SAFE_COMPONENT_LENGTH","constants","MAX_LENGTH","debug$1","process","env","NODE_DEBUG","test","args","console","error","debug_1","module","debug","re","src","t","R","createToken","name","value","isGlobal","index","RegExp","undefined","NUMERICIDENTIFIER","NUMERICIDENTIFIERLOOSE","NONNUMERICIDENTIFIER","PRERELEASEIDENTIFIER","PRERELEASEIDENTIFIERLOOSE","BUILDIDENTIFIER","MAINVERSION","PRERELEASE","BUILD","FULLPLAIN","MAINVERSIONLOOSE","PRERELEASELOOSE","LOOSEPLAIN","XRANGEIDENTIFIER","XRANGEIDENTIFIERLOOSE","GTLT","XRANGEPLAIN","XRANGEPLAINLOOSE","COERCE","LONETILDE","tildeTrimReplace","LONECARET","caretTrimReplace","comparatorTrimReplace","opts","parseOptions$2","options","loose","filter","k","reduce","o","parseOptions_1","numeric","compareIdentifiers$1","a","b","anum","bnum","rcompareIdentifiers","identifiers","compareIdentifiers","MAX_LENGTH$1","re$2","t$2","parseOptions$1","SemVer$c","constructor","version","includePrerelease","TypeError","length","m","trim","match","LOOSE","FULL","raw","major","minor","patch","prerelease","split","map","id","num","build","format","join","toString","compare","other","compareMain","comparePre","i","compareBuild","inc","release","identifier","push","isNaN","Error","semver$2","re$1","t$1","SemVer$b","parseOptions","parse$5","r","er","parse_1","parse$4","valid$1","v","valid_1","parse$3","clean","s","replace","clean_1","SemVer$a","inc_1","SemVer$9","compare$a","compare_1","compare$9","eq$2","eq_1","parse$2","eq$1","diff","version1","version2","v1","v2","hasPre","prefix","defaultResult","key","diff_1","SemVer$8","major_1","SemVer$7","minor_1","SemVer$6","patch_1","parse$1","parsed","prerelease_1","compare$8","rcompare","rcompare_1","compare$7","compareLoose","compareLoose_1","SemVer$5","compareBuild$2","versionA","versionB","compareBuild_1","compareBuild$1","sort","list","sort_1","rsort","rsort_1","compare$6","gt$3","gt_1","compare$5","lt$2","lt_1","compare$4","neq$1","neq_1","compare$3","gte$2","gte_1","compare$2","lte$2","lte_1","eq","neq","gt$2","gte$1","lt$1","lte$1","cmp","op","cmp_1","SemVer$4","parse","coerce","String","rtl","next","COERCERTL","exec","lastIndex","coerce_1","iterator","hasRequiredIterator","requireIterator","Yallist","prototype","Symbol","walker","head","yallist","hasRequiredYallist","requireYallist","Node","create","self","tail","forEach","item","arguments","l","removeNode","node","prev","unshiftNode","pushNode","unshift","pop","res","shift","fn","thisp","call","forEachReverse","get","n","getReverse","mapReverse","initial","acc","reduceReverse","toArray","arr","Array","toArrayReverse","slice","from","to","ret","sliceReverse","splice","start","deleteCount","nodes","insert","reverse","p","inserted","lruCache","hasRequiredLruCache","requireLruCache","MAX","LENGTH","LENGTH_CALCULATOR","ALLOW_STALE","MAX_AGE","DISPOSE","NO_DISPOSE_ON_SET","LRU_LIST","CACHE","UPDATE_AGE_ON_GET","naiveLength","LRUCache","max","Infinity","lc","stale","maxAge","dispose","noDisposeOnSet","updateAgeOnGet","reset","mL","allowStale","mA","lengthCalculator","lC","hit","itemCount","rforEach","forEachStep","keys","values","Map","dump","isStale","e","now","h","dumpLru","set","Date","len","has","del","Entry","peek","load","expiresAt","prune","doUse","delete","range","hasRequiredRange","requireRange","Range","Comparator","parseRange","c","first","isNullSet","isAny","comps","memoOpts","Object","memoKey","cached","cache","hr","HYPHENRANGELOOSE","HYPHENRANGE","hyphenReplace","COMPARATORTRIM","TILDETRIM","CARETTRIM","rangeList","comp","parseComparator","replaceGTE0","COMPARATORLOOSE","rangeMap","comparators","size","result","intersects","some","thisComparators","isSatisfiable","rangeComparators","every","thisComparator","rangeComparator","SemVer","testSet","LRU","requireComparator","remainingComparators","testComparator","otherComparator","replaceCarets","replaceTildes","replaceXRanges","replaceStars","isX","toLowerCase","replaceTilde","TILDELOOSE","TILDE","_","M","pr","replaceCaret","CARETLOOSE","CARET","z","replaceXRange","XRANGELOOSE","XRANGE","gtlt","xM","xm","xp","anyX","STAR","GTE0PRE","GTE0","incPr","$0","fM","fm","fp","fpr","fb","tM","tm","tp","tpr","tb","semver","ANY","allowed","comparator","hasRequiredComparator","operator","COMPARATOR","sameDirectionIncreasing","sameDirectionDecreasing","sameSemVer","differentDirectionsInclusive","oppositeDirectionsLessThan","oppositeDirectionsGreaterThan","Range$8","satisfies$3","satisfies_1","Range$7","toComparators","toComparators_1","SemVer$3","Range$6","maxSatisfying","versions","maxSV","rangeObj","maxSatisfying_1","SemVer$2","Range$5","minSatisfying","min","minSV","minSatisfying_1","SemVer$1","Range$4","gt$1","minVersion","minver","setMin","compver","minVersion_1","Range$3","validRange","valid","Comparator$1","ANY$1","Range$2","satisfies$2","gt","lt","lte","gte","outside$2","hilo","gtfn","ltefn","ltfn","ecomp","high","low","outside_1","outside$1","gtr","gtr_1","outside","ltr","ltr_1","Range$1","r1","r2","intersects_1","satisfies$1","compare$1","simplify","included","ranges","simplified","original","satisfies","subset","sub","dom","sawNonNull","OUTER","simpleSub","simpleDom","isSub","simpleSubset","eqSet","Set","higherGT","lowerLT","add","gtltComp","higher","lower","hasDomLT","hasDomGT","needDomLTPre","needDomGTPre","subset_1","internalRe","semver$1","tokens","simplifyRange","builtins","experimental","coreModules","reader","read","jsonPath","find","path","dirname","dir","string","fs","readFileSync","toNamespacedPath","code","parent","isWindows","platform","own$1","hasOwnProperty","codes","messages","nodeInternalPrefix","userStackTraceLimit","ERR_INVALID_MODULE_SPECIFIER","createError","request","reason","base","ERR_INVALID_PACKAGE_CONFIG","message","ERR_INVALID_PACKAGE_TARGET","pkgPath","target","isImport","relError","startsWith","assert","JSON","stringify","ERR_MODULE_NOT_FOUND","type","ERR_PACKAGE_IMPORT_NOT_DEFINED","specifier","packagePath","ERR_PACKAGE_PATH_NOT_EXPORTED","subpath","ERR_UNSUPPORTED_DIR_IMPORT","ERR_UNKNOWN_FILE_EXTENSION","ERR_INVALID_ARG_VALUE","inspected","inspect","includes","ERR_UNSUPPORTED_ESM_URL_SCHEME","url","protocol","sym","def","makeNodeErrorWithCode","Base","NodeError","limit","stackTraceLimit","isErrorStackTraceLimitWritable","getMessage","defineProperty","enumerable","writable","configurable","addCodeToName","hideStackFrames","captureLargerStackTrace","stack","desc","getOwnPropertyDescriptor","isExtensible","hidden","stackTraceLimitIsWritable","POSITIVE_INFINITY","captureStackTrace","Reflect","apply","expectedLength","extensionFormatMap","__proto__","defaultGetFormat","URL","mime","pathname","ext","extname","getPackageType","href","fileURLToPath","listOfBuiltins","own","DEFAULT_CONDITIONS","freeze","DEFAULT_CONDITIONS_SET","invalidSegmentRegEx","patternRegEx","encodedSepRegEx","emittedPackageWarnings","packageJsonCache","emitFolderMapDeprecation","pjsonUrl","isExports","pjsonPath","emitWarning","emitLegacyIndexDeprecation","packageJsonUrl","main","basePath","getConditionsSet","conditions","isArray","tryStatSync","statSync","Stats","getPackageConfig","existing","source","packageConfig","exists","imports","packageJson","getPackageScopeConfig","resolved","packageJsonPath","endsWith","lastPackageJsonUrl","fileExists","isFile","legacyMainResolve","guess","tries","finalizeResolution","stats","isDirectory","throwImportNotDefined","throwExportsNotFound","throwInvalidSubpath","internal","throwInvalidPackageTarget","resolvePackageTargetString","pattern","isURL","exportTarget","packageResolve","resolvedPath","isArrayIndex","keyNumber","resolvePackageTarget","packageSubpath","targetList","lastException","targetItem","getOwnPropertyNames","conditionalTarget","isConditionalExportsMainSugar","isConditionalSugar","j","curIsConditionalSugar","packageExportsResolve","exact","bestMatch","packageImportsResolve","pathToFileURL","parsePackageName","separatorIndex","indexOf","validPackageName","isScoped","packageName","lastPath","stat","isRelativeSpecifier","shouldBeTreatedAsRelativeOrAbsolutePath","moduleResolve","defaultResolve","context","parentURL","urlPath","real","realpathSync","old","sep","search","hash","resolve","Promise","reject"],"sources":["../../src/vendor/import-meta-resolve.js"],"sourcesContent":["\n/****************************************************************************\\\n * NOTE FROM BABEL AUTHORS *\n * This file is inlined from https://github.com/wooorm/import-meta-resolve, *\n * because we need to compile it to CommonJS. *\n\\****************************************************************************/\n\n/*\n(The MIT License)\n\nCopyright (c) 2021 Titus Wormer \n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n---\n\nThis is a derivative work based on:\n.\nWhich is licensed:\n\n\"\"\"\nCopyright Node.js contributors. All rights reserved.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to\ndeal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n\"\"\"\n\nThis license applies to parts of Node.js originating from the\nhttps://github.com/joyent/node repository:\n\n\"\"\"\nCopyright Joyent, Inc. and other Node contributors. All rights reserved.\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to\ndeal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n\"\"\"\n*/\n\nimport { URL, fileURLToPath, pathToFileURL } from 'url';\nimport fs, { realpathSync, statSync, Stats } from 'fs';\nimport path from 'path';\nimport assert from 'assert';\nimport { format, inspect } from 'util';\n\nvar re$3 = {exports: {}};\n\n// Note: this is the semver.org version of the spec that it implements\n// Not necessarily the package version of this code.\nconst SEMVER_SPEC_VERSION = '2.0.0';\n\nconst MAX_LENGTH$2 = 256;\nconst MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER ||\n/* istanbul ignore next */ 9007199254740991;\n\n// Max safe segment length for coercion.\nconst MAX_SAFE_COMPONENT_LENGTH = 16;\n\nvar constants = {\n SEMVER_SPEC_VERSION,\n MAX_LENGTH: MAX_LENGTH$2,\n MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1,\n MAX_SAFE_COMPONENT_LENGTH,\n};\n\nconst debug$1 = (\n typeof process === 'object' &&\n process.env &&\n process.env.NODE_DEBUG &&\n /\\bsemver\\b/i.test(process.env.NODE_DEBUG)\n) ? (...args) => console.error('SEMVER', ...args)\n : () => {};\n\nvar debug_1 = debug$1;\n\n(function (module, exports) {\n\tconst { MAX_SAFE_COMPONENT_LENGTH } = constants;\n\tconst debug = debug_1;\n\texports = module.exports = {};\n\n\t// The actual regexps go on exports.re\n\tconst re = exports.re = [];\n\tconst src = exports.src = [];\n\tconst t = exports.t = {};\n\tlet R = 0;\n\n\tconst createToken = (name, value, isGlobal) => {\n\t const index = R++;\n\t debug(name, index, value);\n\t t[name] = index;\n\t src[index] = value;\n\t re[index] = new RegExp(value, isGlobal ? 'g' : undefined);\n\t};\n\n\t// The following Regular Expressions can be used for tokenizing,\n\t// validating, and parsing SemVer version strings.\n\n\t// ## Numeric Identifier\n\t// A single `0`, or a non-zero digit followed by zero or more digits.\n\n\tcreateToken('NUMERICIDENTIFIER', '0|[1-9]\\\\d*');\n\tcreateToken('NUMERICIDENTIFIERLOOSE', '[0-9]+');\n\n\t// ## Non-numeric Identifier\n\t// Zero or more digits, followed by a letter or hyphen, and then zero or\n\t// more letters, digits, or hyphens.\n\n\tcreateToken('NONNUMERICIDENTIFIER', '\\\\d*[a-zA-Z-][a-zA-Z0-9-]*');\n\n\t// ## Main Version\n\t// Three dot-separated numeric identifiers.\n\n\tcreateToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n\t `(${src[t.NUMERICIDENTIFIER]})\\\\.` +\n\t `(${src[t.NUMERICIDENTIFIER]})`);\n\n\tcreateToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n\t `(${src[t.NUMERICIDENTIFIERLOOSE]})\\\\.` +\n\t `(${src[t.NUMERICIDENTIFIERLOOSE]})`);\n\n\t// ## Pre-release Version Identifier\n\t// A numeric identifier, or a non-numeric identifier.\n\n\tcreateToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]\n\t}|${src[t.NONNUMERICIDENTIFIER]})`);\n\n\tcreateToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]\n\t}|${src[t.NONNUMERICIDENTIFIER]})`);\n\n\t// ## Pre-release Version\n\t// Hyphen, followed by one or more dot-separated pre-release version\n\t// identifiers.\n\n\tcreateToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]\n\t}(?:\\\\.${src[t.PRERELEASEIDENTIFIER]})*))`);\n\n\tcreateToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]\n\t}(?:\\\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);\n\n\t// ## Build Metadata Identifier\n\t// Any combination of digits, letters, or hyphens.\n\n\tcreateToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+');\n\n\t// ## Build Metadata\n\t// Plus sign, followed by one or more period-separated build metadata\n\t// identifiers.\n\n\tcreateToken('BUILD', `(?:\\\\+(${src[t.BUILDIDENTIFIER]\n\t}(?:\\\\.${src[t.BUILDIDENTIFIER]})*))`);\n\n\t// ## Full Version String\n\t// A main version, followed optionally by a pre-release version and\n\t// build metadata.\n\n\t// Note that the only major, minor, patch, and pre-release sections of\n\t// the version string are capturing groups. The build metadata is not a\n\t// capturing group, because it should not ever be used in version\n\t// comparison.\n\n\tcreateToken('FULLPLAIN', `v?${src[t.MAINVERSION]\n\t}${src[t.PRERELEASE]}?${\n\t src[t.BUILD]}?`);\n\n\tcreateToken('FULL', `^${src[t.FULLPLAIN]}$`);\n\n\t// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.\n\t// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty\n\t// common in the npm registry.\n\tcreateToken('LOOSEPLAIN', `[v=\\\\s]*${src[t.MAINVERSIONLOOSE]\n\t}${src[t.PRERELEASELOOSE]}?${\n\t src[t.BUILD]}?`);\n\n\tcreateToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);\n\n\tcreateToken('GTLT', '((?:<|>)?=?)');\n\n\t// Something like \"2.*\" or \"1.2.x\".\n\t// Note that \"x.x\" is a valid xRange identifer, meaning \"any version\"\n\t// Only the first item is strictly required.\n\tcreateToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`);\n\tcreateToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\\\*`);\n\n\tcreateToken('XRANGEPLAIN', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIER]})` +\n\t `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n\t `(?:\\\\.(${src[t.XRANGEIDENTIFIER]})` +\n\t `(?:${src[t.PRERELEASE]})?${\n\t src[t.BUILD]}?` +\n\t `)?)?`);\n\n\tcreateToken('XRANGEPLAINLOOSE', `[v=\\\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n\t `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n\t `(?:\\\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +\n\t `(?:${src[t.PRERELEASELOOSE]})?${\n\t src[t.BUILD]}?` +\n\t `)?)?`);\n\n\tcreateToken('XRANGE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAIN]}$`);\n\tcreateToken('XRANGELOOSE', `^${src[t.GTLT]}\\\\s*${src[t.XRANGEPLAINLOOSE]}$`);\n\n\t// Coercion.\n\t// Extract anything that could conceivably be a part of a valid semver\n\tcreateToken('COERCE', `${'(^|[^\\\\d])' +\n\t '(\\\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +\n\t `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n\t `(?:\\\\.(\\\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +\n\t `(?:$|[^\\\\d])`);\n\tcreateToken('COERCERTL', src[t.COERCE], true);\n\n\t// Tilde ranges.\n\t// Meaning is \"reasonably at or greater than\"\n\tcreateToken('LONETILDE', '(?:~>?)');\n\n\tcreateToken('TILDETRIM', `(\\\\s*)${src[t.LONETILDE]}\\\\s+`, true);\n\texports.tildeTrimReplace = '$1~';\n\n\tcreateToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);\n\tcreateToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);\n\n\t// Caret ranges.\n\t// Meaning is \"at least and backwards compatible with\"\n\tcreateToken('LONECARET', '(?:\\\\^)');\n\n\tcreateToken('CARETTRIM', `(\\\\s*)${src[t.LONECARET]}\\\\s+`, true);\n\texports.caretTrimReplace = '$1^';\n\n\tcreateToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);\n\tcreateToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);\n\n\t// A simple gt/lt/eq thing, or just \"\" to indicate \"any version\"\n\tcreateToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\\\s*(${src[t.LOOSEPLAIN]})$|^$`);\n\tcreateToken('COMPARATOR', `^${src[t.GTLT]}\\\\s*(${src[t.FULLPLAIN]})$|^$`);\n\n\t// An expression to strip any whitespace between the gtlt and the thing\n\t// it modifies, so that `> 1.2.3` ==> `>1.2.3`\n\tcreateToken('COMPARATORTRIM', `(\\\\s*)${src[t.GTLT]\n\t}\\\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);\n\texports.comparatorTrimReplace = '$1$2$3';\n\n\t// Something like `1.2.3 - 1.2.4`\n\t// Note that these all use the loose form, because they'll be\n\t// checked against either the strict or loose comparator form\n\t// later.\n\tcreateToken('HYPHENRANGE', `^\\\\s*(${src[t.XRANGEPLAIN]})` +\n\t `\\\\s+-\\\\s+` +\n\t `(${src[t.XRANGEPLAIN]})` +\n\t `\\\\s*$`);\n\n\tcreateToken('HYPHENRANGELOOSE', `^\\\\s*(${src[t.XRANGEPLAINLOOSE]})` +\n\t `\\\\s+-\\\\s+` +\n\t `(${src[t.XRANGEPLAINLOOSE]})` +\n\t `\\\\s*$`);\n\n\t// Star ranges basically just allow anything at all.\n\tcreateToken('STAR', '(<|>)?=?\\\\s*\\\\*');\n\t// >=0.0.0 is like a star\n\tcreateToken('GTE0', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$');\n\tcreateToken('GTE0PRE', '^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$');\n} (re$3, re$3.exports));\n\n// parse out just the options we care about so we always get a consistent\n// obj with keys in a consistent order.\nconst opts = ['includePrerelease', 'loose', 'rtl'];\nconst parseOptions$2 = options =>\n !options ? {}\n : typeof options !== 'object' ? { loose: true }\n : opts.filter(k => options[k]).reduce((o, k) => {\n o[k] = true;\n return o\n }, {});\nvar parseOptions_1 = parseOptions$2;\n\nconst numeric = /^[0-9]+$/;\nconst compareIdentifiers$1 = (a, b) => {\n const anum = numeric.test(a);\n const bnum = numeric.test(b);\n\n if (anum && bnum) {\n a = +a;\n b = +b;\n }\n\n return a === b ? 0\n : (anum && !bnum) ? -1\n : (bnum && !anum) ? 1\n : a < b ? -1\n : 1\n};\n\nconst rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a);\n\nvar identifiers = {\n compareIdentifiers: compareIdentifiers$1,\n rcompareIdentifiers,\n};\n\nconst debug = debug_1;\nconst { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER } = constants;\nconst { re: re$2, t: t$2 } = re$3.exports;\n\nconst parseOptions$1 = parseOptions_1;\nconst { compareIdentifiers } = identifiers;\nclass SemVer$c {\n constructor (version, options) {\n options = parseOptions$1(options);\n\n if (version instanceof SemVer$c) {\n if (version.loose === !!options.loose &&\n version.includePrerelease === !!options.includePrerelease) {\n return version\n } else {\n version = version.version;\n }\n } else if (typeof version !== 'string') {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n if (version.length > MAX_LENGTH$1) {\n throw new TypeError(\n `version is longer than ${MAX_LENGTH$1} characters`\n )\n }\n\n debug('SemVer', version, options);\n this.options = options;\n this.loose = !!options.loose;\n // this isn't actually relevant for versions, but keep it so that we\n // don't run into trouble passing this.options around.\n this.includePrerelease = !!options.includePrerelease;\n\n const m = version.trim().match(options.loose ? re$2[t$2.LOOSE] : re$2[t$2.FULL]);\n\n if (!m) {\n throw new TypeError(`Invalid Version: ${version}`)\n }\n\n this.raw = version;\n\n // these are actually numbers\n this.major = +m[1];\n this.minor = +m[2];\n this.patch = +m[3];\n\n if (this.major > MAX_SAFE_INTEGER || this.major < 0) {\n throw new TypeError('Invalid major version')\n }\n\n if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {\n throw new TypeError('Invalid minor version')\n }\n\n if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {\n throw new TypeError('Invalid patch version')\n }\n\n // numberify any prerelease numeric ids\n if (!m[4]) {\n this.prerelease = [];\n } else {\n this.prerelease = m[4].split('.').map((id) => {\n if (/^[0-9]+$/.test(id)) {\n const num = +id;\n if (num >= 0 && num < MAX_SAFE_INTEGER) {\n return num\n }\n }\n return id\n });\n }\n\n this.build = m[5] ? m[5].split('.') : [];\n this.format();\n }\n\n format () {\n this.version = `${this.major}.${this.minor}.${this.patch}`;\n if (this.prerelease.length) {\n this.version += `-${this.prerelease.join('.')}`;\n }\n return this.version\n }\n\n toString () {\n return this.version\n }\n\n compare (other) {\n debug('SemVer.compare', this.version, this.options, other);\n if (!(other instanceof SemVer$c)) {\n if (typeof other === 'string' && other === this.version) {\n return 0\n }\n other = new SemVer$c(other, this.options);\n }\n\n if (other.version === this.version) {\n return 0\n }\n\n return this.compareMain(other) || this.comparePre(other)\n }\n\n compareMain (other) {\n if (!(other instanceof SemVer$c)) {\n other = new SemVer$c(other, this.options);\n }\n\n return (\n compareIdentifiers(this.major, other.major) ||\n compareIdentifiers(this.minor, other.minor) ||\n compareIdentifiers(this.patch, other.patch)\n )\n }\n\n comparePre (other) {\n if (!(other instanceof SemVer$c)) {\n other = new SemVer$c(other, this.options);\n }\n\n // NOT having a prerelease is > having one\n if (this.prerelease.length && !other.prerelease.length) {\n return -1\n } else if (!this.prerelease.length && other.prerelease.length) {\n return 1\n } else if (!this.prerelease.length && !other.prerelease.length) {\n return 0\n }\n\n let i = 0;\n do {\n const a = this.prerelease[i];\n const b = other.prerelease[i];\n debug('prerelease compare', i, a, b);\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n compareBuild (other) {\n if (!(other instanceof SemVer$c)) {\n other = new SemVer$c(other, this.options);\n }\n\n let i = 0;\n do {\n const a = this.build[i];\n const b = other.build[i];\n debug('prerelease compare', i, a, b);\n if (a === undefined && b === undefined) {\n return 0\n } else if (b === undefined) {\n return 1\n } else if (a === undefined) {\n return -1\n } else if (a === b) {\n continue\n } else {\n return compareIdentifiers(a, b)\n }\n } while (++i)\n }\n\n // preminor will bump the version up to the next minor release, and immediately\n // down to pre-release. premajor and prepatch work the same way.\n inc (release, identifier) {\n switch (release) {\n case 'premajor':\n this.prerelease.length = 0;\n this.patch = 0;\n this.minor = 0;\n this.major++;\n this.inc('pre', identifier);\n break\n case 'preminor':\n this.prerelease.length = 0;\n this.patch = 0;\n this.minor++;\n this.inc('pre', identifier);\n break\n case 'prepatch':\n // If this is already a prerelease, it will bump to the next version\n // drop any prereleases that might already exist, since they are not\n // relevant at this point.\n this.prerelease.length = 0;\n this.inc('patch', identifier);\n this.inc('pre', identifier);\n break\n // If the input is a non-prerelease version, this acts the same as\n // prepatch.\n case 'prerelease':\n if (this.prerelease.length === 0) {\n this.inc('patch', identifier);\n }\n this.inc('pre', identifier);\n break\n\n case 'major':\n // If this is a pre-major version, bump up to the same major version.\n // Otherwise increment major.\n // 1.0.0-5 bumps to 1.0.0\n // 1.1.0 bumps to 2.0.0\n if (\n this.minor !== 0 ||\n this.patch !== 0 ||\n this.prerelease.length === 0\n ) {\n this.major++;\n }\n this.minor = 0;\n this.patch = 0;\n this.prerelease = [];\n break\n case 'minor':\n // If this is a pre-minor version, bump up to the same minor version.\n // Otherwise increment minor.\n // 1.2.0-5 bumps to 1.2.0\n // 1.2.1 bumps to 1.3.0\n if (this.patch !== 0 || this.prerelease.length === 0) {\n this.minor++;\n }\n this.patch = 0;\n this.prerelease = [];\n break\n case 'patch':\n // If this is not a pre-release version, it will increment the patch.\n // If it is a pre-release it will bump up to the same patch version.\n // 1.2.0-5 patches to 1.2.0\n // 1.2.0 patches to 1.2.1\n if (this.prerelease.length === 0) {\n this.patch++;\n }\n this.prerelease = [];\n break\n // This probably shouldn't be used publicly.\n // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.\n case 'pre':\n if (this.prerelease.length === 0) {\n this.prerelease = [0];\n } else {\n let i = this.prerelease.length;\n while (--i >= 0) {\n if (typeof this.prerelease[i] === 'number') {\n this.prerelease[i]++;\n i = -2;\n }\n }\n if (i === -1) {\n // didn't increment anything\n this.prerelease.push(0);\n }\n }\n if (identifier) {\n // 1.2.0-beta.1 bumps to 1.2.0-beta.2,\n // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0\n if (compareIdentifiers(this.prerelease[0], identifier) === 0) {\n if (isNaN(this.prerelease[1])) {\n this.prerelease = [identifier, 0];\n }\n } else {\n this.prerelease = [identifier, 0];\n }\n }\n break\n\n default:\n throw new Error(`invalid increment argument: ${release}`)\n }\n this.format();\n this.raw = this.version;\n return this\n }\n}\n\nvar semver$2 = SemVer$c;\n\nconst { MAX_LENGTH } = constants;\nconst { re: re$1, t: t$1 } = re$3.exports;\nconst SemVer$b = semver$2;\n\nconst parseOptions = parseOptions_1;\nconst parse$5 = (version, options) => {\n options = parseOptions(options);\n\n if (version instanceof SemVer$b) {\n return version\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n if (version.length > MAX_LENGTH) {\n return null\n }\n\n const r = options.loose ? re$1[t$1.LOOSE] : re$1[t$1.FULL];\n if (!r.test(version)) {\n return null\n }\n\n try {\n return new SemVer$b(version, options)\n } catch (er) {\n return null\n }\n};\n\nvar parse_1 = parse$5;\n\nconst parse$4 = parse_1;\nconst valid$1 = (version, options) => {\n const v = parse$4(version, options);\n return v ? v.version : null\n};\nvar valid_1 = valid$1;\n\nconst parse$3 = parse_1;\nconst clean = (version, options) => {\n const s = parse$3(version.trim().replace(/^[=v]+/, ''), options);\n return s ? s.version : null\n};\nvar clean_1 = clean;\n\nconst SemVer$a = semver$2;\n\nconst inc = (version, release, options, identifier) => {\n if (typeof (options) === 'string') {\n identifier = options;\n options = undefined;\n }\n\n try {\n return new SemVer$a(\n version instanceof SemVer$a ? version.version : version,\n options\n ).inc(release, identifier).version\n } catch (er) {\n return null\n }\n};\nvar inc_1 = inc;\n\nconst SemVer$9 = semver$2;\nconst compare$a = (a, b, loose) =>\n new SemVer$9(a, loose).compare(new SemVer$9(b, loose));\n\nvar compare_1 = compare$a;\n\nconst compare$9 = compare_1;\nconst eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0;\nvar eq_1 = eq$2;\n\nconst parse$2 = parse_1;\nconst eq$1 = eq_1;\n\nconst diff = (version1, version2) => {\n if (eq$1(version1, version2)) {\n return null\n } else {\n const v1 = parse$2(version1);\n const v2 = parse$2(version2);\n const hasPre = v1.prerelease.length || v2.prerelease.length;\n const prefix = hasPre ? 'pre' : '';\n const defaultResult = hasPre ? 'prerelease' : '';\n for (const key in v1) {\n if (key === 'major' || key === 'minor' || key === 'patch') {\n if (v1[key] !== v2[key]) {\n return prefix + key\n }\n }\n }\n return defaultResult // may be undefined\n }\n};\nvar diff_1 = diff;\n\nconst SemVer$8 = semver$2;\nconst major = (a, loose) => new SemVer$8(a, loose).major;\nvar major_1 = major;\n\nconst SemVer$7 = semver$2;\nconst minor = (a, loose) => new SemVer$7(a, loose).minor;\nvar minor_1 = minor;\n\nconst SemVer$6 = semver$2;\nconst patch = (a, loose) => new SemVer$6(a, loose).patch;\nvar patch_1 = patch;\n\nconst parse$1 = parse_1;\nconst prerelease = (version, options) => {\n const parsed = parse$1(version, options);\n return (parsed && parsed.prerelease.length) ? parsed.prerelease : null\n};\nvar prerelease_1 = prerelease;\n\nconst compare$8 = compare_1;\nconst rcompare = (a, b, loose) => compare$8(b, a, loose);\nvar rcompare_1 = rcompare;\n\nconst compare$7 = compare_1;\nconst compareLoose = (a, b) => compare$7(a, b, true);\nvar compareLoose_1 = compareLoose;\n\nconst SemVer$5 = semver$2;\nconst compareBuild$2 = (a, b, loose) => {\n const versionA = new SemVer$5(a, loose);\n const versionB = new SemVer$5(b, loose);\n return versionA.compare(versionB) || versionA.compareBuild(versionB)\n};\nvar compareBuild_1 = compareBuild$2;\n\nconst compareBuild$1 = compareBuild_1;\nconst sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose));\nvar sort_1 = sort;\n\nconst compareBuild = compareBuild_1;\nconst rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));\nvar rsort_1 = rsort;\n\nconst compare$6 = compare_1;\nconst gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0;\nvar gt_1 = gt$3;\n\nconst compare$5 = compare_1;\nconst lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0;\nvar lt_1 = lt$2;\n\nconst compare$4 = compare_1;\nconst neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0;\nvar neq_1 = neq$1;\n\nconst compare$3 = compare_1;\nconst gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0;\nvar gte_1 = gte$2;\n\nconst compare$2 = compare_1;\nconst lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0;\nvar lte_1 = lte$2;\n\nconst eq = eq_1;\nconst neq = neq_1;\nconst gt$2 = gt_1;\nconst gte$1 = gte_1;\nconst lt$1 = lt_1;\nconst lte$1 = lte_1;\n\nconst cmp = (a, op, b, loose) => {\n switch (op) {\n case '===':\n if (typeof a === 'object') {\n a = a.version;\n }\n if (typeof b === 'object') {\n b = b.version;\n }\n return a === b\n\n case '!==':\n if (typeof a === 'object') {\n a = a.version;\n }\n if (typeof b === 'object') {\n b = b.version;\n }\n return a !== b\n\n case '':\n case '=':\n case '==':\n return eq(a, b, loose)\n\n case '!=':\n return neq(a, b, loose)\n\n case '>':\n return gt$2(a, b, loose)\n\n case '>=':\n return gte$1(a, b, loose)\n\n case '<':\n return lt$1(a, b, loose)\n\n case '<=':\n return lte$1(a, b, loose)\n\n default:\n throw new TypeError(`Invalid operator: ${op}`)\n }\n};\nvar cmp_1 = cmp;\n\nconst SemVer$4 = semver$2;\nconst parse = parse_1;\nconst { re, t } = re$3.exports;\n\nconst coerce = (version, options) => {\n if (version instanceof SemVer$4) {\n return version\n }\n\n if (typeof version === 'number') {\n version = String(version);\n }\n\n if (typeof version !== 'string') {\n return null\n }\n\n options = options || {};\n\n let match = null;\n if (!options.rtl) {\n match = version.match(re[t.COERCE]);\n } else {\n // Find the right-most coercible string that does not share\n // a terminus with a more left-ward coercible string.\n // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'\n //\n // Walk through the string checking with a /g regexp\n // Manually set the index so as to pick up overlapping matches.\n // Stop when we get a match that ends at the string end, since no\n // coercible string can be more right-ward without the same terminus.\n let next;\n while ((next = re[t.COERCERTL].exec(version)) &&\n (!match || match.index + match[0].length !== version.length)\n ) {\n if (!match ||\n next.index + next[0].length !== match.index + match[0].length) {\n match = next;\n }\n re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;\n }\n // leave it in a clean state\n re[t.COERCERTL].lastIndex = -1;\n }\n\n if (match === null) {\n return null\n }\n\n return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)\n};\nvar coerce_1 = coerce;\n\nvar iterator;\nvar hasRequiredIterator;\n\nfunction requireIterator () {\n\tif (hasRequiredIterator) return iterator;\n\thasRequiredIterator = 1;\n\titerator = function (Yallist) {\n\t Yallist.prototype[Symbol.iterator] = function* () {\n\t for (let walker = this.head; walker; walker = walker.next) {\n\t yield walker.value;\n\t }\n\t };\n\t};\n\treturn iterator;\n}\n\nvar yallist;\nvar hasRequiredYallist;\n\nfunction requireYallist () {\n\tif (hasRequiredYallist) return yallist;\n\thasRequiredYallist = 1;\n\tyallist = Yallist;\n\n\tYallist.Node = Node;\n\tYallist.create = Yallist;\n\n\tfunction Yallist (list) {\n\t var self = this;\n\t if (!(self instanceof Yallist)) {\n\t self = new Yallist();\n\t }\n\n\t self.tail = null;\n\t self.head = null;\n\t self.length = 0;\n\n\t if (list && typeof list.forEach === 'function') {\n\t list.forEach(function (item) {\n\t self.push(item);\n\t });\n\t } else if (arguments.length > 0) {\n\t for (var i = 0, l = arguments.length; i < l; i++) {\n\t self.push(arguments[i]);\n\t }\n\t }\n\n\t return self\n\t}\n\n\tYallist.prototype.removeNode = function (node) {\n\t if (node.list !== this) {\n\t throw new Error('removing node which does not belong to this list')\n\t }\n\n\t var next = node.next;\n\t var prev = node.prev;\n\n\t if (next) {\n\t next.prev = prev;\n\t }\n\n\t if (prev) {\n\t prev.next = next;\n\t }\n\n\t if (node === this.head) {\n\t this.head = next;\n\t }\n\t if (node === this.tail) {\n\t this.tail = prev;\n\t }\n\n\t node.list.length--;\n\t node.next = null;\n\t node.prev = null;\n\t node.list = null;\n\n\t return next\n\t};\n\n\tYallist.prototype.unshiftNode = function (node) {\n\t if (node === this.head) {\n\t return\n\t }\n\n\t if (node.list) {\n\t node.list.removeNode(node);\n\t }\n\n\t var head = this.head;\n\t node.list = this;\n\t node.next = head;\n\t if (head) {\n\t head.prev = node;\n\t }\n\n\t this.head = node;\n\t if (!this.tail) {\n\t this.tail = node;\n\t }\n\t this.length++;\n\t};\n\n\tYallist.prototype.pushNode = function (node) {\n\t if (node === this.tail) {\n\t return\n\t }\n\n\t if (node.list) {\n\t node.list.removeNode(node);\n\t }\n\n\t var tail = this.tail;\n\t node.list = this;\n\t node.prev = tail;\n\t if (tail) {\n\t tail.next = node;\n\t }\n\n\t this.tail = node;\n\t if (!this.head) {\n\t this.head = node;\n\t }\n\t this.length++;\n\t};\n\n\tYallist.prototype.push = function () {\n\t for (var i = 0, l = arguments.length; i < l; i++) {\n\t push(this, arguments[i]);\n\t }\n\t return this.length\n\t};\n\n\tYallist.prototype.unshift = function () {\n\t for (var i = 0, l = arguments.length; i < l; i++) {\n\t unshift(this, arguments[i]);\n\t }\n\t return this.length\n\t};\n\n\tYallist.prototype.pop = function () {\n\t if (!this.tail) {\n\t return undefined\n\t }\n\n\t var res = this.tail.value;\n\t this.tail = this.tail.prev;\n\t if (this.tail) {\n\t this.tail.next = null;\n\t } else {\n\t this.head = null;\n\t }\n\t this.length--;\n\t return res\n\t};\n\n\tYallist.prototype.shift = function () {\n\t if (!this.head) {\n\t return undefined\n\t }\n\n\t var res = this.head.value;\n\t this.head = this.head.next;\n\t if (this.head) {\n\t this.head.prev = null;\n\t } else {\n\t this.tail = null;\n\t }\n\t this.length--;\n\t return res\n\t};\n\n\tYallist.prototype.forEach = function (fn, thisp) {\n\t thisp = thisp || this;\n\t for (var walker = this.head, i = 0; walker !== null; i++) {\n\t fn.call(thisp, walker.value, i, this);\n\t walker = walker.next;\n\t }\n\t};\n\n\tYallist.prototype.forEachReverse = function (fn, thisp) {\n\t thisp = thisp || this;\n\t for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {\n\t fn.call(thisp, walker.value, i, this);\n\t walker = walker.prev;\n\t }\n\t};\n\n\tYallist.prototype.get = function (n) {\n\t for (var i = 0, walker = this.head; walker !== null && i < n; i++) {\n\t // abort out of the list early if we hit a cycle\n\t walker = walker.next;\n\t }\n\t if (i === n && walker !== null) {\n\t return walker.value\n\t }\n\t};\n\n\tYallist.prototype.getReverse = function (n) {\n\t for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {\n\t // abort out of the list early if we hit a cycle\n\t walker = walker.prev;\n\t }\n\t if (i === n && walker !== null) {\n\t return walker.value\n\t }\n\t};\n\n\tYallist.prototype.map = function (fn, thisp) {\n\t thisp = thisp || this;\n\t var res = new Yallist();\n\t for (var walker = this.head; walker !== null;) {\n\t res.push(fn.call(thisp, walker.value, this));\n\t walker = walker.next;\n\t }\n\t return res\n\t};\n\n\tYallist.prototype.mapReverse = function (fn, thisp) {\n\t thisp = thisp || this;\n\t var res = new Yallist();\n\t for (var walker = this.tail; walker !== null;) {\n\t res.push(fn.call(thisp, walker.value, this));\n\t walker = walker.prev;\n\t }\n\t return res\n\t};\n\n\tYallist.prototype.reduce = function (fn, initial) {\n\t var acc;\n\t var walker = this.head;\n\t if (arguments.length > 1) {\n\t acc = initial;\n\t } else if (this.head) {\n\t walker = this.head.next;\n\t acc = this.head.value;\n\t } else {\n\t throw new TypeError('Reduce of empty list with no initial value')\n\t }\n\n\t for (var i = 0; walker !== null; i++) {\n\t acc = fn(acc, walker.value, i);\n\t walker = walker.next;\n\t }\n\n\t return acc\n\t};\n\n\tYallist.prototype.reduceReverse = function (fn, initial) {\n\t var acc;\n\t var walker = this.tail;\n\t if (arguments.length > 1) {\n\t acc = initial;\n\t } else if (this.tail) {\n\t walker = this.tail.prev;\n\t acc = this.tail.value;\n\t } else {\n\t throw new TypeError('Reduce of empty list with no initial value')\n\t }\n\n\t for (var i = this.length - 1; walker !== null; i--) {\n\t acc = fn(acc, walker.value, i);\n\t walker = walker.prev;\n\t }\n\n\t return acc\n\t};\n\n\tYallist.prototype.toArray = function () {\n\t var arr = new Array(this.length);\n\t for (var i = 0, walker = this.head; walker !== null; i++) {\n\t arr[i] = walker.value;\n\t walker = walker.next;\n\t }\n\t return arr\n\t};\n\n\tYallist.prototype.toArrayReverse = function () {\n\t var arr = new Array(this.length);\n\t for (var i = 0, walker = this.tail; walker !== null; i++) {\n\t arr[i] = walker.value;\n\t walker = walker.prev;\n\t }\n\t return arr\n\t};\n\n\tYallist.prototype.slice = function (from, to) {\n\t to = to || this.length;\n\t if (to < 0) {\n\t to += this.length;\n\t }\n\t from = from || 0;\n\t if (from < 0) {\n\t from += this.length;\n\t }\n\t var ret = new Yallist();\n\t if (to < from || to < 0) {\n\t return ret\n\t }\n\t if (from < 0) {\n\t from = 0;\n\t }\n\t if (to > this.length) {\n\t to = this.length;\n\t }\n\t for (var i = 0, walker = this.head; walker !== null && i < from; i++) {\n\t walker = walker.next;\n\t }\n\t for (; walker !== null && i < to; i++, walker = walker.next) {\n\t ret.push(walker.value);\n\t }\n\t return ret\n\t};\n\n\tYallist.prototype.sliceReverse = function (from, to) {\n\t to = to || this.length;\n\t if (to < 0) {\n\t to += this.length;\n\t }\n\t from = from || 0;\n\t if (from < 0) {\n\t from += this.length;\n\t }\n\t var ret = new Yallist();\n\t if (to < from || to < 0) {\n\t return ret\n\t }\n\t if (from < 0) {\n\t from = 0;\n\t }\n\t if (to > this.length) {\n\t to = this.length;\n\t }\n\t for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {\n\t walker = walker.prev;\n\t }\n\t for (; walker !== null && i > from; i--, walker = walker.prev) {\n\t ret.push(walker.value);\n\t }\n\t return ret\n\t};\n\n\tYallist.prototype.splice = function (start, deleteCount, ...nodes) {\n\t if (start > this.length) {\n\t start = this.length - 1;\n\t }\n\t if (start < 0) {\n\t start = this.length + start;\n\t }\n\n\t for (var i = 0, walker = this.head; walker !== null && i < start; i++) {\n\t walker = walker.next;\n\t }\n\n\t var ret = [];\n\t for (var i = 0; walker && i < deleteCount; i++) {\n\t ret.push(walker.value);\n\t walker = this.removeNode(walker);\n\t }\n\t if (walker === null) {\n\t walker = this.tail;\n\t }\n\n\t if (walker !== this.head && walker !== this.tail) {\n\t walker = walker.prev;\n\t }\n\n\t for (var i = 0; i < nodes.length; i++) {\n\t walker = insert(this, walker, nodes[i]);\n\t }\n\t return ret;\n\t};\n\n\tYallist.prototype.reverse = function () {\n\t var head = this.head;\n\t var tail = this.tail;\n\t for (var walker = head; walker !== null; walker = walker.prev) {\n\t var p = walker.prev;\n\t walker.prev = walker.next;\n\t walker.next = p;\n\t }\n\t this.head = tail;\n\t this.tail = head;\n\t return this\n\t};\n\n\tfunction insert (self, node, value) {\n\t var inserted = node === self.head ?\n\t new Node(value, null, node, self) :\n\t new Node(value, node, node.next, self);\n\n\t if (inserted.next === null) {\n\t self.tail = inserted;\n\t }\n\t if (inserted.prev === null) {\n\t self.head = inserted;\n\t }\n\n\t self.length++;\n\n\t return inserted\n\t}\n\n\tfunction push (self, item) {\n\t self.tail = new Node(item, self.tail, null, self);\n\t if (!self.head) {\n\t self.head = self.tail;\n\t }\n\t self.length++;\n\t}\n\n\tfunction unshift (self, item) {\n\t self.head = new Node(item, null, self.head, self);\n\t if (!self.tail) {\n\t self.tail = self.head;\n\t }\n\t self.length++;\n\t}\n\n\tfunction Node (value, prev, next, list) {\n\t if (!(this instanceof Node)) {\n\t return new Node(value, prev, next, list)\n\t }\n\n\t this.list = list;\n\t this.value = value;\n\n\t if (prev) {\n\t prev.next = this;\n\t this.prev = prev;\n\t } else {\n\t this.prev = null;\n\t }\n\n\t if (next) {\n\t next.prev = this;\n\t this.next = next;\n\t } else {\n\t this.next = null;\n\t }\n\t}\n\n\ttry {\n\t // add if support for Symbol.iterator is present\n\t requireIterator()(Yallist);\n\t} catch (er) {}\n\treturn yallist;\n}\n\nvar lruCache;\nvar hasRequiredLruCache;\n\nfunction requireLruCache () {\n\tif (hasRequiredLruCache) return lruCache;\n\thasRequiredLruCache = 1;\n\n\t// A linked list to keep track of recently-used-ness\n\tconst Yallist = requireYallist();\n\n\tconst MAX = Symbol('max');\n\tconst LENGTH = Symbol('length');\n\tconst LENGTH_CALCULATOR = Symbol('lengthCalculator');\n\tconst ALLOW_STALE = Symbol('allowStale');\n\tconst MAX_AGE = Symbol('maxAge');\n\tconst DISPOSE = Symbol('dispose');\n\tconst NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet');\n\tconst LRU_LIST = Symbol('lruList');\n\tconst CACHE = Symbol('cache');\n\tconst UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet');\n\n\tconst naiveLength = () => 1;\n\n\t// lruList is a yallist where the head is the youngest\n\t// item, and the tail is the oldest. the list contains the Hit\n\t// objects as the entries.\n\t// Each Hit object has a reference to its Yallist.Node. This\n\t// never changes.\n\t//\n\t// cache is a Map (or PseudoMap) that matches the keys to\n\t// the Yallist.Node object.\n\tclass LRUCache {\n\t constructor (options) {\n\t if (typeof options === 'number')\n\t options = { max: options };\n\n\t if (!options)\n\t options = {};\n\n\t if (options.max && (typeof options.max !== 'number' || options.max < 0))\n\t throw new TypeError('max must be a non-negative number')\n\t // Kind of weird to have a default max of Infinity, but oh well.\n\t this[MAX] = options.max || Infinity;\n\n\t const lc = options.length || naiveLength;\n\t this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc;\n\t this[ALLOW_STALE] = options.stale || false;\n\t if (options.maxAge && typeof options.maxAge !== 'number')\n\t throw new TypeError('maxAge must be a number')\n\t this[MAX_AGE] = options.maxAge || 0;\n\t this[DISPOSE] = options.dispose;\n\t this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;\n\t this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false;\n\t this.reset();\n\t }\n\n\t // resize the cache when the max changes.\n\t set max (mL) {\n\t if (typeof mL !== 'number' || mL < 0)\n\t throw new TypeError('max must be a non-negative number')\n\n\t this[MAX] = mL || Infinity;\n\t trim(this);\n\t }\n\t get max () {\n\t return this[MAX]\n\t }\n\n\t set allowStale (allowStale) {\n\t this[ALLOW_STALE] = !!allowStale;\n\t }\n\t get allowStale () {\n\t return this[ALLOW_STALE]\n\t }\n\n\t set maxAge (mA) {\n\t if (typeof mA !== 'number')\n\t throw new TypeError('maxAge must be a non-negative number')\n\n\t this[MAX_AGE] = mA;\n\t trim(this);\n\t }\n\t get maxAge () {\n\t return this[MAX_AGE]\n\t }\n\n\t // resize the cache when the lengthCalculator changes.\n\t set lengthCalculator (lC) {\n\t if (typeof lC !== 'function')\n\t lC = naiveLength;\n\n\t if (lC !== this[LENGTH_CALCULATOR]) {\n\t this[LENGTH_CALCULATOR] = lC;\n\t this[LENGTH] = 0;\n\t this[LRU_LIST].forEach(hit => {\n\t hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);\n\t this[LENGTH] += hit.length;\n\t });\n\t }\n\t trim(this);\n\t }\n\t get lengthCalculator () { return this[LENGTH_CALCULATOR] }\n\n\t get length () { return this[LENGTH] }\n\t get itemCount () { return this[LRU_LIST].length }\n\n\t rforEach (fn, thisp) {\n\t thisp = thisp || this;\n\t for (let walker = this[LRU_LIST].tail; walker !== null;) {\n\t const prev = walker.prev;\n\t forEachStep(this, fn, walker, thisp);\n\t walker = prev;\n\t }\n\t }\n\n\t forEach (fn, thisp) {\n\t thisp = thisp || this;\n\t for (let walker = this[LRU_LIST].head; walker !== null;) {\n\t const next = walker.next;\n\t forEachStep(this, fn, walker, thisp);\n\t walker = next;\n\t }\n\t }\n\n\t keys () {\n\t return this[LRU_LIST].toArray().map(k => k.key)\n\t }\n\n\t values () {\n\t return this[LRU_LIST].toArray().map(k => k.value)\n\t }\n\n\t reset () {\n\t if (this[DISPOSE] &&\n\t this[LRU_LIST] &&\n\t this[LRU_LIST].length) {\n\t this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value));\n\t }\n\n\t this[CACHE] = new Map(); // hash of items by key\n\t this[LRU_LIST] = new Yallist(); // list of items in order of use recency\n\t this[LENGTH] = 0; // length of items in the list\n\t }\n\n\t dump () {\n\t return this[LRU_LIST].map(hit =>\n\t isStale(this, hit) ? false : {\n\t k: hit.key,\n\t v: hit.value,\n\t e: hit.now + (hit.maxAge || 0)\n\t }).toArray().filter(h => h)\n\t }\n\n\t dumpLru () {\n\t return this[LRU_LIST]\n\t }\n\n\t set (key, value, maxAge) {\n\t maxAge = maxAge || this[MAX_AGE];\n\n\t if (maxAge && typeof maxAge !== 'number')\n\t throw new TypeError('maxAge must be a number')\n\n\t const now = maxAge ? Date.now() : 0;\n\t const len = this[LENGTH_CALCULATOR](value, key);\n\n\t if (this[CACHE].has(key)) {\n\t if (len > this[MAX]) {\n\t del(this, this[CACHE].get(key));\n\t return false\n\t }\n\n\t const node = this[CACHE].get(key);\n\t const item = node.value;\n\n\t // dispose of the old one before overwriting\n\t // split out into 2 ifs for better coverage tracking\n\t if (this[DISPOSE]) {\n\t if (!this[NO_DISPOSE_ON_SET])\n\t this[DISPOSE](key, item.value);\n\t }\n\n\t item.now = now;\n\t item.maxAge = maxAge;\n\t item.value = value;\n\t this[LENGTH] += len - item.length;\n\t item.length = len;\n\t this.get(key);\n\t trim(this);\n\t return true\n\t }\n\n\t const hit = new Entry(key, value, len, now, maxAge);\n\n\t // oversized objects fall out of cache automatically.\n\t if (hit.length > this[MAX]) {\n\t if (this[DISPOSE])\n\t this[DISPOSE](key, value);\n\n\t return false\n\t }\n\n\t this[LENGTH] += hit.length;\n\t this[LRU_LIST].unshift(hit);\n\t this[CACHE].set(key, this[LRU_LIST].head);\n\t trim(this);\n\t return true\n\t }\n\n\t has (key) {\n\t if (!this[CACHE].has(key)) return false\n\t const hit = this[CACHE].get(key).value;\n\t return !isStale(this, hit)\n\t }\n\n\t get (key) {\n\t return get(this, key, true)\n\t }\n\n\t peek (key) {\n\t return get(this, key, false)\n\t }\n\n\t pop () {\n\t const node = this[LRU_LIST].tail;\n\t if (!node)\n\t return null\n\n\t del(this, node);\n\t return node.value\n\t }\n\n\t del (key) {\n\t del(this, this[CACHE].get(key));\n\t }\n\n\t load (arr) {\n\t // reset the cache\n\t this.reset();\n\n\t const now = Date.now();\n\t // A previous serialized cache has the most recent items first\n\t for (let l = arr.length - 1; l >= 0; l--) {\n\t const hit = arr[l];\n\t const expiresAt = hit.e || 0;\n\t if (expiresAt === 0)\n\t // the item was created without expiration in a non aged cache\n\t this.set(hit.k, hit.v);\n\t else {\n\t const maxAge = expiresAt - now;\n\t // dont add already expired items\n\t if (maxAge > 0) {\n\t this.set(hit.k, hit.v, maxAge);\n\t }\n\t }\n\t }\n\t }\n\n\t prune () {\n\t this[CACHE].forEach((value, key) => get(this, key, false));\n\t }\n\t}\n\n\tconst get = (self, key, doUse) => {\n\t const node = self[CACHE].get(key);\n\t if (node) {\n\t const hit = node.value;\n\t if (isStale(self, hit)) {\n\t del(self, node);\n\t if (!self[ALLOW_STALE])\n\t return undefined\n\t } else {\n\t if (doUse) {\n\t if (self[UPDATE_AGE_ON_GET])\n\t node.value.now = Date.now();\n\t self[LRU_LIST].unshiftNode(node);\n\t }\n\t }\n\t return hit.value\n\t }\n\t};\n\n\tconst isStale = (self, hit) => {\n\t if (!hit || (!hit.maxAge && !self[MAX_AGE]))\n\t return false\n\n\t const diff = Date.now() - hit.now;\n\t return hit.maxAge ? diff > hit.maxAge\n\t : self[MAX_AGE] && (diff > self[MAX_AGE])\n\t};\n\n\tconst trim = self => {\n\t if (self[LENGTH] > self[MAX]) {\n\t for (let walker = self[LRU_LIST].tail;\n\t self[LENGTH] > self[MAX] && walker !== null;) {\n\t // We know that we're about to delete this one, and also\n\t // what the next least recently used key will be, so just\n\t // go ahead and set it now.\n\t const prev = walker.prev;\n\t del(self, walker);\n\t walker = prev;\n\t }\n\t }\n\t};\n\n\tconst del = (self, node) => {\n\t if (node) {\n\t const hit = node.value;\n\t if (self[DISPOSE])\n\t self[DISPOSE](hit.key, hit.value);\n\n\t self[LENGTH] -= hit.length;\n\t self[CACHE].delete(hit.key);\n\t self[LRU_LIST].removeNode(node);\n\t }\n\t};\n\n\tclass Entry {\n\t constructor (key, value, length, now, maxAge) {\n\t this.key = key;\n\t this.value = value;\n\t this.length = length;\n\t this.now = now;\n\t this.maxAge = maxAge || 0;\n\t }\n\t}\n\n\tconst forEachStep = (self, fn, node, thisp) => {\n\t let hit = node.value;\n\t if (isStale(self, hit)) {\n\t del(self, node);\n\t if (!self[ALLOW_STALE])\n\t hit = undefined;\n\t }\n\t if (hit)\n\t fn.call(thisp, hit.value, hit.key, self);\n\t};\n\n\tlruCache = LRUCache;\n\treturn lruCache;\n}\n\nvar range;\nvar hasRequiredRange;\n\nfunction requireRange () {\n\tif (hasRequiredRange) return range;\n\thasRequiredRange = 1;\n\t// hoisted class for cyclic dependency\n\tclass Range {\n\t constructor (range, options) {\n\t options = parseOptions(options);\n\n\t if (range instanceof Range) {\n\t if (\n\t range.loose === !!options.loose &&\n\t range.includePrerelease === !!options.includePrerelease\n\t ) {\n\t return range\n\t } else {\n\t return new Range(range.raw, options)\n\t }\n\t }\n\n\t if (range instanceof Comparator) {\n\t // just put it in the set and return\n\t this.raw = range.value;\n\t this.set = [[range]];\n\t this.format();\n\t return this\n\t }\n\n\t this.options = options;\n\t this.loose = !!options.loose;\n\t this.includePrerelease = !!options.includePrerelease;\n\n\t // First, split based on boolean or ||\n\t this.raw = range;\n\t this.set = range\n\t .split('||')\n\t // map the range to a 2d array of comparators\n\t .map(r => this.parseRange(r.trim()))\n\t // throw out any comparator lists that are empty\n\t // this generally means that it was not a valid range, which is allowed\n\t // in loose mode, but will still throw if the WHOLE range is invalid.\n\t .filter(c => c.length);\n\n\t if (!this.set.length) {\n\t throw new TypeError(`Invalid SemVer Range: ${range}`)\n\t }\n\n\t // if we have any that are not the null set, throw out null sets.\n\t if (this.set.length > 1) {\n\t // keep the first one, in case they're all null sets\n\t const first = this.set[0];\n\t this.set = this.set.filter(c => !isNullSet(c[0]));\n\t if (this.set.length === 0) {\n\t this.set = [first];\n\t } else if (this.set.length > 1) {\n\t // if we have any that are *, then the range is just *\n\t for (const c of this.set) {\n\t if (c.length === 1 && isAny(c[0])) {\n\t this.set = [c];\n\t break\n\t }\n\t }\n\t }\n\t }\n\n\t this.format();\n\t }\n\n\t format () {\n\t this.range = this.set\n\t .map((comps) => {\n\t return comps.join(' ').trim()\n\t })\n\t .join('||')\n\t .trim();\n\t return this.range\n\t }\n\n\t toString () {\n\t return this.range\n\t }\n\n\t parseRange (range) {\n\t range = range.trim();\n\n\t // memoize range parsing for performance.\n\t // this is a very hot path, and fully deterministic.\n\t const memoOpts = Object.keys(this.options).join(',');\n\t const memoKey = `parseRange:${memoOpts}:${range}`;\n\t const cached = cache.get(memoKey);\n\t if (cached) {\n\t return cached\n\t }\n\n\t const loose = this.options.loose;\n\t // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`\n\t const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];\n\t range = range.replace(hr, hyphenReplace(this.options.includePrerelease));\n\t debug('hyphen replace', range);\n\t // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`\n\t range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);\n\t debug('comparator trim', range);\n\n\t // `~ 1.2.3` => `~1.2.3`\n\t range = range.replace(re[t.TILDETRIM], tildeTrimReplace);\n\n\t // `^ 1.2.3` => `^1.2.3`\n\t range = range.replace(re[t.CARETTRIM], caretTrimReplace);\n\n\t // normalize spaces\n\t range = range.split(/\\s+/).join(' ');\n\n\t // At this point, the range is completely trimmed and\n\t // ready to be split into comparators.\n\n\t let rangeList = range\n\t .split(' ')\n\t .map(comp => parseComparator(comp, this.options))\n\t .join(' ')\n\t .split(/\\s+/)\n\t // >=0.0.0 is equivalent to *\n\t .map(comp => replaceGTE0(comp, this.options));\n\n\t if (loose) {\n\t // in loose mode, throw out any that are not valid comparators\n\t rangeList = rangeList.filter(comp => {\n\t debug('loose invalid filter', comp, this.options);\n\t return !!comp.match(re[t.COMPARATORLOOSE])\n\t });\n\t }\n\t debug('range list', rangeList);\n\n\t // if any comparators are the null set, then replace with JUST null set\n\t // if more than one comparator, remove any * comparators\n\t // also, don't include the same comparator more than once\n\t const rangeMap = new Map();\n\t const comparators = rangeList.map(comp => new Comparator(comp, this.options));\n\t for (const comp of comparators) {\n\t if (isNullSet(comp)) {\n\t return [comp]\n\t }\n\t rangeMap.set(comp.value, comp);\n\t }\n\t if (rangeMap.size > 1 && rangeMap.has('')) {\n\t rangeMap.delete('');\n\t }\n\n\t const result = [...rangeMap.values()];\n\t cache.set(memoKey, result);\n\t return result\n\t }\n\n\t intersects (range, options) {\n\t if (!(range instanceof Range)) {\n\t throw new TypeError('a Range is required')\n\t }\n\n\t return this.set.some((thisComparators) => {\n\t return (\n\t isSatisfiable(thisComparators, options) &&\n\t range.set.some((rangeComparators) => {\n\t return (\n\t isSatisfiable(rangeComparators, options) &&\n\t thisComparators.every((thisComparator) => {\n\t return rangeComparators.every((rangeComparator) => {\n\t return thisComparator.intersects(rangeComparator, options)\n\t })\n\t })\n\t )\n\t })\n\t )\n\t })\n\t }\n\n\t // if ANY of the sets match ALL of its comparators, then pass\n\t test (version) {\n\t if (!version) {\n\t return false\n\t }\n\n\t if (typeof version === 'string') {\n\t try {\n\t version = new SemVer(version, this.options);\n\t } catch (er) {\n\t return false\n\t }\n\t }\n\n\t for (let i = 0; i < this.set.length; i++) {\n\t if (testSet(this.set[i], version, this.options)) {\n\t return true\n\t }\n\t }\n\t return false\n\t }\n\t}\n\trange = Range;\n\n\tconst LRU = requireLruCache();\n\tconst cache = new LRU({ max: 1000 });\n\n\tconst parseOptions = parseOptions_1;\n\tconst Comparator = requireComparator();\n\tconst debug = debug_1;\n\tconst SemVer = semver$2;\n\tconst {\n\t re,\n\t t,\n\t comparatorTrimReplace,\n\t tildeTrimReplace,\n\t caretTrimReplace,\n\t} = re$3.exports;\n\n\tconst isNullSet = c => c.value === '<0.0.0-0';\n\tconst isAny = c => c.value === '';\n\n\t// take a set of comparators and determine whether there\n\t// exists a version which can satisfy it\n\tconst isSatisfiable = (comparators, options) => {\n\t let result = true;\n\t const remainingComparators = comparators.slice();\n\t let testComparator = remainingComparators.pop();\n\n\t while (result && remainingComparators.length) {\n\t result = remainingComparators.every((otherComparator) => {\n\t return testComparator.intersects(otherComparator, options)\n\t });\n\n\t testComparator = remainingComparators.pop();\n\t }\n\n\t return result\n\t};\n\n\t// comprised of xranges, tildes, stars, and gtlt's at this point.\n\t// already replaced the hyphen ranges\n\t// turn into a set of JUST comparators.\n\tconst parseComparator = (comp, options) => {\n\t debug('comp', comp, options);\n\t comp = replaceCarets(comp, options);\n\t debug('caret', comp);\n\t comp = replaceTildes(comp, options);\n\t debug('tildes', comp);\n\t comp = replaceXRanges(comp, options);\n\t debug('xrange', comp);\n\t comp = replaceStars(comp, options);\n\t debug('stars', comp);\n\t return comp\n\t};\n\n\tconst isX = id => !id || id.toLowerCase() === 'x' || id === '*';\n\n\t// ~, ~> --> * (any, kinda silly)\n\t// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0\n\t// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0\n\t// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0\n\t// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0\n\t// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0\n\tconst replaceTildes = (comp, options) =>\n\t comp.trim().split(/\\s+/).map((c) => {\n\t return replaceTilde(c, options)\n\t }).join(' ');\n\n\tconst replaceTilde = (comp, options) => {\n\t const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];\n\t return comp.replace(r, (_, M, m, p, pr) => {\n\t debug('tilde', comp, _, M, m, p, pr);\n\t let ret;\n\n\t if (isX(M)) {\n\t ret = '';\n\t } else if (isX(m)) {\n\t ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;\n\t } else if (isX(p)) {\n\t // ~1.2 == >=1.2.0 <1.3.0-0\n\t ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;\n\t } else if (pr) {\n\t debug('replaceTilde pr', pr);\n\t ret = `>=${M}.${m}.${p}-${pr\n\t } <${M}.${+m + 1}.0-0`;\n\t } else {\n\t // ~1.2.3 == >=1.2.3 <1.3.0-0\n\t ret = `>=${M}.${m}.${p\n\t } <${M}.${+m + 1}.0-0`;\n\t }\n\n\t debug('tilde return', ret);\n\t return ret\n\t })\n\t};\n\n\t// ^ --> * (any, kinda silly)\n\t// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0\n\t// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0\n\t// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0\n\t// ^1.2.3 --> >=1.2.3 <2.0.0-0\n\t// ^1.2.0 --> >=1.2.0 <2.0.0-0\n\tconst replaceCarets = (comp, options) =>\n\t comp.trim().split(/\\s+/).map((c) => {\n\t return replaceCaret(c, options)\n\t }).join(' ');\n\n\tconst replaceCaret = (comp, options) => {\n\t debug('caret', comp, options);\n\t const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];\n\t const z = options.includePrerelease ? '-0' : '';\n\t return comp.replace(r, (_, M, m, p, pr) => {\n\t debug('caret', comp, _, M, m, p, pr);\n\t let ret;\n\n\t if (isX(M)) {\n\t ret = '';\n\t } else if (isX(m)) {\n\t ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;\n\t } else if (isX(p)) {\n\t if (M === '0') {\n\t ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;\n\t } else {\n\t ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;\n\t }\n\t } else if (pr) {\n\t debug('replaceCaret pr', pr);\n\t if (M === '0') {\n\t if (m === '0') {\n\t ret = `>=${M}.${m}.${p}-${pr\n\t } <${M}.${m}.${+p + 1}-0`;\n\t } else {\n\t ret = `>=${M}.${m}.${p}-${pr\n\t } <${M}.${+m + 1}.0-0`;\n\t }\n\t } else {\n\t ret = `>=${M}.${m}.${p}-${pr\n\t } <${+M + 1}.0.0-0`;\n\t }\n\t } else {\n\t debug('no pr');\n\t if (M === '0') {\n\t if (m === '0') {\n\t ret = `>=${M}.${m}.${p\n\t }${z} <${M}.${m}.${+p + 1}-0`;\n\t } else {\n\t ret = `>=${M}.${m}.${p\n\t }${z} <${M}.${+m + 1}.0-0`;\n\t }\n\t } else {\n\t ret = `>=${M}.${m}.${p\n\t } <${+M + 1}.0.0-0`;\n\t }\n\t }\n\n\t debug('caret return', ret);\n\t return ret\n\t })\n\t};\n\n\tconst replaceXRanges = (comp, options) => {\n\t debug('replaceXRanges', comp, options);\n\t return comp.split(/\\s+/).map((c) => {\n\t return replaceXRange(c, options)\n\t }).join(' ')\n\t};\n\n\tconst replaceXRange = (comp, options) => {\n\t comp = comp.trim();\n\t const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];\n\t return comp.replace(r, (ret, gtlt, M, m, p, pr) => {\n\t debug('xRange', comp, ret, gtlt, M, m, p, pr);\n\t const xM = isX(M);\n\t const xm = xM || isX(m);\n\t const xp = xm || isX(p);\n\t const anyX = xp;\n\n\t if (gtlt === '=' && anyX) {\n\t gtlt = '';\n\t }\n\n\t // if we're including prereleases in the match, then we need\n\t // to fix this to -0, the lowest possible prerelease value\n\t pr = options.includePrerelease ? '-0' : '';\n\n\t if (xM) {\n\t if (gtlt === '>' || gtlt === '<') {\n\t // nothing is allowed\n\t ret = '<0.0.0-0';\n\t } else {\n\t // nothing is forbidden\n\t ret = '*';\n\t }\n\t } else if (gtlt && anyX) {\n\t // we know patch is an x, because we have any x at all.\n\t // replace X with 0\n\t if (xm) {\n\t m = 0;\n\t }\n\t p = 0;\n\n\t if (gtlt === '>') {\n\t // >1 => >=2.0.0\n\t // >1.2 => >=1.3.0\n\t gtlt = '>=';\n\t if (xm) {\n\t M = +M + 1;\n\t m = 0;\n\t p = 0;\n\t } else {\n\t m = +m + 1;\n\t p = 0;\n\t }\n\t } else if (gtlt === '<=') {\n\t // <=0.7.x is actually <0.8.0, since any 0.7.x should\n\t // pass. Similarly, <=7.x is actually <8.0.0, etc.\n\t gtlt = '<';\n\t if (xm) {\n\t M = +M + 1;\n\t } else {\n\t m = +m + 1;\n\t }\n\t }\n\n\t if (gtlt === '<') {\n\t pr = '-0';\n\t }\n\n\t ret = `${gtlt + M}.${m}.${p}${pr}`;\n\t } else if (xm) {\n\t ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;\n\t } else if (xp) {\n\t ret = `>=${M}.${m}.0${pr\n\t } <${M}.${+m + 1}.0-0`;\n\t }\n\n\t debug('xRange return', ret);\n\n\t return ret\n\t })\n\t};\n\n\t// Because * is AND-ed with everything else in the comparator,\n\t// and '' means \"any version\", just remove the *s entirely.\n\tconst replaceStars = (comp, options) => {\n\t debug('replaceStars', comp, options);\n\t // Looseness is ignored here. star is always as loose as it gets!\n\t return comp.trim().replace(re[t.STAR], '')\n\t};\n\n\tconst replaceGTE0 = (comp, options) => {\n\t debug('replaceGTE0', comp, options);\n\t return comp.trim()\n\t .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')\n\t};\n\n\t// This function is passed to string.replace(re[t.HYPHENRANGE])\n\t// M, m, patch, prerelease, build\n\t// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5\n\t// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do\n\t// 1.2 - 3.4 => >=1.2.0 <3.5.0-0\n\tconst hyphenReplace = incPr => ($0,\n\t from, fM, fm, fp, fpr, fb,\n\t to, tM, tm, tp, tpr, tb) => {\n\t if (isX(fM)) {\n\t from = '';\n\t } else if (isX(fm)) {\n\t from = `>=${fM}.0.0${incPr ? '-0' : ''}`;\n\t } else if (isX(fp)) {\n\t from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`;\n\t } else if (fpr) {\n\t from = `>=${from}`;\n\t } else {\n\t from = `>=${from}${incPr ? '-0' : ''}`;\n\t }\n\n\t if (isX(tM)) {\n\t to = '';\n\t } else if (isX(tm)) {\n\t to = `<${+tM + 1}.0.0-0`;\n\t } else if (isX(tp)) {\n\t to = `<${tM}.${+tm + 1}.0-0`;\n\t } else if (tpr) {\n\t to = `<=${tM}.${tm}.${tp}-${tpr}`;\n\t } else if (incPr) {\n\t to = `<${tM}.${tm}.${+tp + 1}-0`;\n\t } else {\n\t to = `<=${to}`;\n\t }\n\n\t return (`${from} ${to}`).trim()\n\t};\n\n\tconst testSet = (set, version, options) => {\n\t for (let i = 0; i < set.length; i++) {\n\t if (!set[i].test(version)) {\n\t return false\n\t }\n\t }\n\n\t if (version.prerelease.length && !options.includePrerelease) {\n\t // Find the set of versions that are allowed to have prereleases\n\t // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0\n\t // That should allow `1.2.3-pr.2` to pass.\n\t // However, `1.2.4-alpha.notready` should NOT be allowed,\n\t // even though it's within the range set by the comparators.\n\t for (let i = 0; i < set.length; i++) {\n\t debug(set[i].semver);\n\t if (set[i].semver === Comparator.ANY) {\n\t continue\n\t }\n\n\t if (set[i].semver.prerelease.length > 0) {\n\t const allowed = set[i].semver;\n\t if (allowed.major === version.major &&\n\t allowed.minor === version.minor &&\n\t allowed.patch === version.patch) {\n\t return true\n\t }\n\t }\n\t }\n\n\t // Version has a -pre, but it's not one of the ones we like.\n\t return false\n\t }\n\n\t return true\n\t};\n\treturn range;\n}\n\nvar comparator;\nvar hasRequiredComparator;\n\nfunction requireComparator () {\n\tif (hasRequiredComparator) return comparator;\n\thasRequiredComparator = 1;\n\tconst ANY = Symbol('SemVer ANY');\n\t// hoisted class for cyclic dependency\n\tclass Comparator {\n\t static get ANY () {\n\t return ANY\n\t }\n\n\t constructor (comp, options) {\n\t options = parseOptions(options);\n\n\t if (comp instanceof Comparator) {\n\t if (comp.loose === !!options.loose) {\n\t return comp\n\t } else {\n\t comp = comp.value;\n\t }\n\t }\n\n\t debug('comparator', comp, options);\n\t this.options = options;\n\t this.loose = !!options.loose;\n\t this.parse(comp);\n\n\t if (this.semver === ANY) {\n\t this.value = '';\n\t } else {\n\t this.value = this.operator + this.semver.version;\n\t }\n\n\t debug('comp', this);\n\t }\n\n\t parse (comp) {\n\t const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];\n\t const m = comp.match(r);\n\n\t if (!m) {\n\t throw new TypeError(`Invalid comparator: ${comp}`)\n\t }\n\n\t this.operator = m[1] !== undefined ? m[1] : '';\n\t if (this.operator === '=') {\n\t this.operator = '';\n\t }\n\n\t // if it literally is just '>' or '' then allow anything.\n\t if (!m[2]) {\n\t this.semver = ANY;\n\t } else {\n\t this.semver = new SemVer(m[2], this.options.loose);\n\t }\n\t }\n\n\t toString () {\n\t return this.value\n\t }\n\n\t test (version) {\n\t debug('Comparator.test', version, this.options.loose);\n\n\t if (this.semver === ANY || version === ANY) {\n\t return true\n\t }\n\n\t if (typeof version === 'string') {\n\t try {\n\t version = new SemVer(version, this.options);\n\t } catch (er) {\n\t return false\n\t }\n\t }\n\n\t return cmp(version, this.operator, this.semver, this.options)\n\t }\n\n\t intersects (comp, options) {\n\t if (!(comp instanceof Comparator)) {\n\t throw new TypeError('a Comparator is required')\n\t }\n\n\t if (!options || typeof options !== 'object') {\n\t options = {\n\t loose: !!options,\n\t includePrerelease: false,\n\t };\n\t }\n\n\t if (this.operator === '') {\n\t if (this.value === '') {\n\t return true\n\t }\n\t return new Range(comp.value, options).test(this.value)\n\t } else if (comp.operator === '') {\n\t if (comp.value === '') {\n\t return true\n\t }\n\t return new Range(this.value, options).test(comp.semver)\n\t }\n\n\t const sameDirectionIncreasing =\n\t (this.operator === '>=' || this.operator === '>') &&\n\t (comp.operator === '>=' || comp.operator === '>');\n\t const sameDirectionDecreasing =\n\t (this.operator === '<=' || this.operator === '<') &&\n\t (comp.operator === '<=' || comp.operator === '<');\n\t const sameSemVer = this.semver.version === comp.semver.version;\n\t const differentDirectionsInclusive =\n\t (this.operator === '>=' || this.operator === '<=') &&\n\t (comp.operator === '>=' || comp.operator === '<=');\n\t const oppositeDirectionsLessThan =\n\t cmp(this.semver, '<', comp.semver, options) &&\n\t (this.operator === '>=' || this.operator === '>') &&\n\t (comp.operator === '<=' || comp.operator === '<');\n\t const oppositeDirectionsGreaterThan =\n\t cmp(this.semver, '>', comp.semver, options) &&\n\t (this.operator === '<=' || this.operator === '<') &&\n\t (comp.operator === '>=' || comp.operator === '>');\n\n\t return (\n\t sameDirectionIncreasing ||\n\t sameDirectionDecreasing ||\n\t (sameSemVer && differentDirectionsInclusive) ||\n\t oppositeDirectionsLessThan ||\n\t oppositeDirectionsGreaterThan\n\t )\n\t }\n\t}\n\n\tcomparator = Comparator;\n\n\tconst parseOptions = parseOptions_1;\n\tconst { re, t } = re$3.exports;\n\tconst cmp = cmp_1;\n\tconst debug = debug_1;\n\tconst SemVer = semver$2;\n\tconst Range = requireRange();\n\treturn comparator;\n}\n\nconst Range$8 = requireRange();\nconst satisfies$3 = (version, range, options) => {\n try {\n range = new Range$8(range, options);\n } catch (er) {\n return false\n }\n return range.test(version)\n};\nvar satisfies_1 = satisfies$3;\n\nconst Range$7 = requireRange();\n\n// Mostly just for testing and legacy API reasons\nconst toComparators = (range, options) =>\n new Range$7(range, options).set\n .map(comp => comp.map(c => c.value).join(' ').trim().split(' '));\n\nvar toComparators_1 = toComparators;\n\nconst SemVer$3 = semver$2;\nconst Range$6 = requireRange();\n\nconst maxSatisfying = (versions, range, options) => {\n let max = null;\n let maxSV = null;\n let rangeObj = null;\n try {\n rangeObj = new Range$6(range, options);\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!max || maxSV.compare(v) === -1) {\n // compare(max, v, true)\n max = v;\n maxSV = new SemVer$3(max, options);\n }\n }\n });\n return max\n};\nvar maxSatisfying_1 = maxSatisfying;\n\nconst SemVer$2 = semver$2;\nconst Range$5 = requireRange();\nconst minSatisfying = (versions, range, options) => {\n let min = null;\n let minSV = null;\n let rangeObj = null;\n try {\n rangeObj = new Range$5(range, options);\n } catch (er) {\n return null\n }\n versions.forEach((v) => {\n if (rangeObj.test(v)) {\n // satisfies(v, range, options)\n if (!min || minSV.compare(v) === 1) {\n // compare(min, v, true)\n min = v;\n minSV = new SemVer$2(min, options);\n }\n }\n });\n return min\n};\nvar minSatisfying_1 = minSatisfying;\n\nconst SemVer$1 = semver$2;\nconst Range$4 = requireRange();\nconst gt$1 = gt_1;\n\nconst minVersion = (range, loose) => {\n range = new Range$4(range, loose);\n\n let minver = new SemVer$1('0.0.0');\n if (range.test(minver)) {\n return minver\n }\n\n minver = new SemVer$1('0.0.0-0');\n if (range.test(minver)) {\n return minver\n }\n\n minver = null;\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i];\n\n let setMin = null;\n comparators.forEach((comparator) => {\n // Clone to avoid manipulating the comparator's semver object.\n const compver = new SemVer$1(comparator.semver.version);\n switch (comparator.operator) {\n case '>':\n if (compver.prerelease.length === 0) {\n compver.patch++;\n } else {\n compver.prerelease.push(0);\n }\n compver.raw = compver.format();\n /* fallthrough */\n case '':\n case '>=':\n if (!setMin || gt$1(compver, setMin)) {\n setMin = compver;\n }\n break\n case '<':\n case '<=':\n /* Ignore maximum versions */\n break\n /* istanbul ignore next */\n default:\n throw new Error(`Unexpected operation: ${comparator.operator}`)\n }\n });\n if (setMin && (!minver || gt$1(minver, setMin))) {\n minver = setMin;\n }\n }\n\n if (minver && range.test(minver)) {\n return minver\n }\n\n return null\n};\nvar minVersion_1 = minVersion;\n\nconst Range$3 = requireRange();\nconst validRange = (range, options) => {\n try {\n // Return '*' instead of '' so that truthiness works.\n // This will throw if it's invalid anyway\n return new Range$3(range, options).range || '*'\n } catch (er) {\n return null\n }\n};\nvar valid = validRange;\n\nconst SemVer = semver$2;\nconst Comparator$1 = requireComparator();\nconst { ANY: ANY$1 } = Comparator$1;\nconst Range$2 = requireRange();\nconst satisfies$2 = satisfies_1;\nconst gt = gt_1;\nconst lt = lt_1;\nconst lte = lte_1;\nconst gte = gte_1;\n\nconst outside$2 = (version, range, hilo, options) => {\n version = new SemVer(version, options);\n range = new Range$2(range, options);\n\n let gtfn, ltefn, ltfn, comp, ecomp;\n switch (hilo) {\n case '>':\n gtfn = gt;\n ltefn = lte;\n ltfn = lt;\n comp = '>';\n ecomp = '>=';\n break\n case '<':\n gtfn = lt;\n ltefn = gte;\n ltfn = gt;\n comp = '<';\n ecomp = '<=';\n break\n default:\n throw new TypeError('Must provide a hilo val of \"<\" or \">\"')\n }\n\n // If it satisfies the range it is not outside\n if (satisfies$2(version, range, options)) {\n return false\n }\n\n // From now on, variable terms are as if we're in \"gtr\" mode.\n // but note that everything is flipped for the \"ltr\" function.\n\n for (let i = 0; i < range.set.length; ++i) {\n const comparators = range.set[i];\n\n let high = null;\n let low = null;\n\n comparators.forEach((comparator) => {\n if (comparator.semver === ANY$1) {\n comparator = new Comparator$1('>=0.0.0');\n }\n high = high || comparator;\n low = low || comparator;\n if (gtfn(comparator.semver, high.semver, options)) {\n high = comparator;\n } else if (ltfn(comparator.semver, low.semver, options)) {\n low = comparator;\n }\n });\n\n // If the edge version comparator has a operator then our version\n // isn't outside it\n if (high.operator === comp || high.operator === ecomp) {\n return false\n }\n\n // If the lowest version comparator has an operator and our version\n // is less than it then it isn't higher than the range\n if ((!low.operator || low.operator === comp) &&\n ltefn(version, low.semver)) {\n return false\n } else if (low.operator === ecomp && ltfn(version, low.semver)) {\n return false\n }\n }\n return true\n};\n\nvar outside_1 = outside$2;\n\n// Determine if version is greater than all the versions possible in the range.\nconst outside$1 = outside_1;\nconst gtr = (version, range, options) => outside$1(version, range, '>', options);\nvar gtr_1 = gtr;\n\nconst outside = outside_1;\n// Determine if version is less than all the versions possible in the range\nconst ltr = (version, range, options) => outside(version, range, '<', options);\nvar ltr_1 = ltr;\n\nconst Range$1 = requireRange();\nconst intersects = (r1, r2, options) => {\n r1 = new Range$1(r1, options);\n r2 = new Range$1(r2, options);\n return r1.intersects(r2)\n};\nvar intersects_1 = intersects;\n\n// given a set of versions and a range, create a \"simplified\" range\n// that includes the same versions that the original range does\n// If the original range is shorter than the simplified one, return that.\nconst satisfies$1 = satisfies_1;\nconst compare$1 = compare_1;\nvar simplify = (versions, range, options) => {\n const set = [];\n let first = null;\n let prev = null;\n const v = versions.sort((a, b) => compare$1(a, b, options));\n for (const version of v) {\n const included = satisfies$1(version, range, options);\n if (included) {\n prev = version;\n if (!first) {\n first = version;\n }\n } else {\n if (prev) {\n set.push([first, prev]);\n }\n prev = null;\n first = null;\n }\n }\n if (first) {\n set.push([first, null]);\n }\n\n const ranges = [];\n for (const [min, max] of set) {\n if (min === max) {\n ranges.push(min);\n } else if (!max && min === v[0]) {\n ranges.push('*');\n } else if (!max) {\n ranges.push(`>=${min}`);\n } else if (min === v[0]) {\n ranges.push(`<=${max}`);\n } else {\n ranges.push(`${min} - ${max}`);\n }\n }\n const simplified = ranges.join(' || ');\n const original = typeof range.raw === 'string' ? range.raw : String(range);\n return simplified.length < original.length ? simplified : range\n};\n\nconst Range = requireRange();\nconst Comparator = requireComparator();\nconst { ANY } = Comparator;\nconst satisfies = satisfies_1;\nconst compare = compare_1;\n\n// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:\n// - Every simple range `r1, r2, ...` is a null set, OR\n// - Every simple range `r1, r2, ...` which is not a null set is a subset of\n// some `R1, R2, ...`\n//\n// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:\n// - If c is only the ANY comparator\n// - If C is only the ANY comparator, return true\n// - Else if in prerelease mode, return false\n// - else replace c with `[>=0.0.0]`\n// - If C is only the ANY comparator\n// - if in prerelease mode, return true\n// - else replace C with `[>=0.0.0]`\n// - Let EQ be the set of = comparators in c\n// - If EQ is more than one, return true (null set)\n// - Let GT be the highest > or >= comparator in c\n// - Let LT be the lowest < or <= comparator in c\n// - If GT and LT, and GT.semver > LT.semver, return true (null set)\n// - If any C is a = range, and GT or LT are set, return false\n// - If EQ\n// - If GT, and EQ does not satisfy GT, return true (null set)\n// - If LT, and EQ does not satisfy LT, return true (null set)\n// - If EQ satisfies every C, return true\n// - Else return false\n// - If GT\n// - If GT.semver is lower than any > or >= comp in C, return false\n// - If GT is >=, and GT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the GT.semver tuple, return false\n// - If LT\n// - If LT.semver is greater than any < or <= comp in C, return false\n// - If LT is <=, and LT.semver does not satisfy every C, return false\n// - If GT.semver has a prerelease, and not in prerelease mode\n// - If no C has a prerelease and the LT.semver tuple, return false\n// - Else return true\n\nconst subset = (sub, dom, options = {}) => {\n if (sub === dom) {\n return true\n }\n\n sub = new Range(sub, options);\n dom = new Range(dom, options);\n let sawNonNull = false;\n\n OUTER: for (const simpleSub of sub.set) {\n for (const simpleDom of dom.set) {\n const isSub = simpleSubset(simpleSub, simpleDom, options);\n sawNonNull = sawNonNull || isSub !== null;\n if (isSub) {\n continue OUTER\n }\n }\n // the null set is a subset of everything, but null simple ranges in\n // a complex range should be ignored. so if we saw a non-null range,\n // then we know this isn't a subset, but if EVERY simple range was null,\n // then it is a subset.\n if (sawNonNull) {\n return false\n }\n }\n return true\n};\n\nconst simpleSubset = (sub, dom, options) => {\n if (sub === dom) {\n return true\n }\n\n if (sub.length === 1 && sub[0].semver === ANY) {\n if (dom.length === 1 && dom[0].semver === ANY) {\n return true\n } else if (options.includePrerelease) {\n sub = [new Comparator('>=0.0.0-0')];\n } else {\n sub = [new Comparator('>=0.0.0')];\n }\n }\n\n if (dom.length === 1 && dom[0].semver === ANY) {\n if (options.includePrerelease) {\n return true\n } else {\n dom = [new Comparator('>=0.0.0')];\n }\n }\n\n const eqSet = new Set();\n let gt, lt;\n for (const c of sub) {\n if (c.operator === '>' || c.operator === '>=') {\n gt = higherGT(gt, c, options);\n } else if (c.operator === '<' || c.operator === '<=') {\n lt = lowerLT(lt, c, options);\n } else {\n eqSet.add(c.semver);\n }\n }\n\n if (eqSet.size > 1) {\n return null\n }\n\n let gtltComp;\n if (gt && lt) {\n gtltComp = compare(gt.semver, lt.semver, options);\n if (gtltComp > 0) {\n return null\n } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {\n return null\n }\n }\n\n // will iterate one or zero times\n for (const eq of eqSet) {\n if (gt && !satisfies(eq, String(gt), options)) {\n return null\n }\n\n if (lt && !satisfies(eq, String(lt), options)) {\n return null\n }\n\n for (const c of dom) {\n if (!satisfies(eq, String(c), options)) {\n return false\n }\n }\n\n return true\n }\n\n let higher, lower;\n let hasDomLT, hasDomGT;\n // if the subset has a prerelease, we need a comparator in the superset\n // with the same tuple and a prerelease, or it's not a subset\n let needDomLTPre = lt &&\n !options.includePrerelease &&\n lt.semver.prerelease.length ? lt.semver : false;\n let needDomGTPre = gt &&\n !options.includePrerelease &&\n gt.semver.prerelease.length ? gt.semver : false;\n // exception: <1.2.3-0 is the same as <1.2.3\n if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&\n lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {\n needDomLTPre = false;\n }\n\n for (const c of dom) {\n hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=';\n hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=';\n if (gt) {\n if (needDomGTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomGTPre.major &&\n c.semver.minor === needDomGTPre.minor &&\n c.semver.patch === needDomGTPre.patch) {\n needDomGTPre = false;\n }\n }\n if (c.operator === '>' || c.operator === '>=') {\n higher = higherGT(gt, c, options);\n if (higher === c && higher !== gt) {\n return false\n }\n } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {\n return false\n }\n }\n if (lt) {\n if (needDomLTPre) {\n if (c.semver.prerelease && c.semver.prerelease.length &&\n c.semver.major === needDomLTPre.major &&\n c.semver.minor === needDomLTPre.minor &&\n c.semver.patch === needDomLTPre.patch) {\n needDomLTPre = false;\n }\n }\n if (c.operator === '<' || c.operator === '<=') {\n lower = lowerLT(lt, c, options);\n if (lower === c && lower !== lt) {\n return false\n }\n } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {\n return false\n }\n }\n if (!c.operator && (lt || gt) && gtltComp !== 0) {\n return false\n }\n }\n\n // if there was a < or >, and nothing in the dom, then must be false\n // UNLESS it was limited by another range in the other direction.\n // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0\n if (gt && hasDomLT && !lt && gtltComp !== 0) {\n return false\n }\n\n if (lt && hasDomGT && !gt && gtltComp !== 0) {\n return false\n }\n\n // we needed a prerelease range in a specific tuple, but didn't get one\n // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,\n // because it includes prereleases in the 1.2.3 tuple\n if (needDomGTPre || needDomLTPre) {\n return false\n }\n\n return true\n};\n\n// >=1.2.3 is lower than >1.2.3\nconst higherGT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options);\n return comp > 0 ? a\n : comp < 0 ? b\n : b.operator === '>' && a.operator === '>=' ? b\n : a\n};\n\n// <=1.2.3 is higher than <1.2.3\nconst lowerLT = (a, b, options) => {\n if (!a) {\n return b\n }\n const comp = compare(a.semver, b.semver, options);\n return comp < 0 ? a\n : comp > 0 ? b\n : b.operator === '<' && a.operator === '<=' ? b\n : a\n};\n\nvar subset_1 = subset;\n\n// just pre-load all the stuff that index.js lazily exports\nconst internalRe = re$3.exports;\nvar semver$1 = {\n re: internalRe.re,\n src: internalRe.src,\n tokens: internalRe.t,\n SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,\n SemVer: semver$2,\n compareIdentifiers: identifiers.compareIdentifiers,\n rcompareIdentifiers: identifiers.rcompareIdentifiers,\n parse: parse_1,\n valid: valid_1,\n clean: clean_1,\n inc: inc_1,\n diff: diff_1,\n major: major_1,\n minor: minor_1,\n patch: patch_1,\n prerelease: prerelease_1,\n compare: compare_1,\n rcompare: rcompare_1,\n compareLoose: compareLoose_1,\n compareBuild: compareBuild_1,\n sort: sort_1,\n rsort: rsort_1,\n gt: gt_1,\n lt: lt_1,\n eq: eq_1,\n neq: neq_1,\n gte: gte_1,\n lte: lte_1,\n cmp: cmp_1,\n coerce: coerce_1,\n Comparator: requireComparator(),\n Range: requireRange(),\n satisfies: satisfies_1,\n toComparators: toComparators_1,\n maxSatisfying: maxSatisfying_1,\n minSatisfying: minSatisfying_1,\n minVersion: minVersion_1,\n validRange: valid,\n outside: outside_1,\n gtr: gtr_1,\n ltr: ltr_1,\n intersects: intersects_1,\n simplifyRange: simplify,\n subset: subset_1,\n};\n\nvar semver = semver$1;\n\nvar builtins = function ({\n version = process.version,\n experimental = false\n} = {}) {\n var coreModules = [\n 'assert',\n 'buffer',\n 'child_process',\n 'cluster',\n 'console',\n 'constants',\n 'crypto',\n 'dgram',\n 'dns',\n 'domain',\n 'events',\n 'fs',\n 'http',\n 'https',\n 'module',\n 'net',\n 'os',\n 'path',\n 'punycode',\n 'querystring',\n 'readline',\n 'repl',\n 'stream',\n 'string_decoder',\n 'sys',\n 'timers',\n 'tls',\n 'tty',\n 'url',\n 'util',\n 'vm',\n 'zlib'\n ];\n\n if (semver.lt(version, '6.0.0')) coreModules.push('freelist');\n if (semver.gte(version, '1.0.0')) coreModules.push('v8');\n if (semver.gte(version, '1.1.0')) coreModules.push('process');\n if (semver.gte(version, '8.0.0')) coreModules.push('inspector');\n if (semver.gte(version, '8.1.0')) coreModules.push('async_hooks');\n if (semver.gte(version, '8.4.0')) coreModules.push('http2');\n if (semver.gte(version, '8.5.0')) coreModules.push('perf_hooks');\n if (semver.gte(version, '10.0.0')) coreModules.push('trace_events');\n\n if (\n semver.gte(version, '10.5.0') &&\n (experimental || semver.gte(version, '12.0.0'))\n ) {\n coreModules.push('worker_threads');\n }\n if (semver.gte(version, '12.16.0') && experimental) {\n coreModules.push('wasi');\n }\n \n return coreModules\n};\n\n// Manually “tree shaken” from:\n\nconst reader = {read};\n\n/**\n * @param {string} jsonPath\n * @returns {{string: string}}\n */\nfunction read(jsonPath) {\n return find(path.dirname(jsonPath))\n}\n\n/**\n * @param {string} dir\n * @returns {{string: string}}\n */\nfunction find(dir) {\n try {\n const string = fs.readFileSync(\n path.toNamespacedPath(path.join(dir, 'package.json')),\n 'utf8'\n );\n return {string}\n } catch (error) {\n if (error.code === 'ENOENT') {\n const parent = path.dirname(dir);\n if (dir !== parent) return find(parent)\n return {string: undefined}\n // Throw all other errors.\n /* c8 ignore next 4 */\n }\n\n throw error\n }\n}\n\n// Manually “tree shaken” from:\n\nconst isWindows = process.platform === 'win32';\n\nconst own$1 = {}.hasOwnProperty;\n\nconst codes = {};\n\n/**\n * @typedef {(...args: unknown[]) => string} MessageFunction\n */\n\n/** @type {Map} */\nconst messages = new Map();\nconst nodeInternalPrefix = '__node_internal_';\n/** @type {number} */\nlet userStackTraceLimit;\n\ncodes.ERR_INVALID_MODULE_SPECIFIER = createError(\n 'ERR_INVALID_MODULE_SPECIFIER',\n /**\n * @param {string} request\n * @param {string} reason\n * @param {string} [base]\n */\n (request, reason, base = undefined) => {\n return `Invalid module \"${request}\" ${reason}${\n base ? ` imported from ${base}` : ''\n }`\n },\n TypeError\n);\n\ncodes.ERR_INVALID_PACKAGE_CONFIG = createError(\n 'ERR_INVALID_PACKAGE_CONFIG',\n /**\n * @param {string} path\n * @param {string} [base]\n * @param {string} [message]\n */\n (path, base, message) => {\n return `Invalid package config ${path}${\n base ? ` while importing ${base}` : ''\n }${message ? `. ${message}` : ''}`\n },\n Error\n);\n\ncodes.ERR_INVALID_PACKAGE_TARGET = createError(\n 'ERR_INVALID_PACKAGE_TARGET',\n /**\n * @param {string} pkgPath\n * @param {string} key\n * @param {unknown} target\n * @param {boolean} [isImport=false]\n * @param {string} [base]\n */\n (pkgPath, key, target, isImport = false, base = undefined) => {\n const relError =\n typeof target === 'string' &&\n !isImport &&\n target.length > 0 &&\n !target.startsWith('./');\n if (key === '.') {\n assert(isImport === false);\n return (\n `Invalid \"exports\" main target ${JSON.stringify(target)} defined ` +\n `in the package config ${pkgPath}package.json${\n base ? ` imported from ${base}` : ''\n }${relError ? '; targets must start with \"./\"' : ''}`\n )\n }\n\n return `Invalid \"${\n isImport ? 'imports' : 'exports'\n }\" target ${JSON.stringify(\n target\n )} defined for '${key}' in the package config ${pkgPath}package.json${\n base ? ` imported from ${base}` : ''\n }${relError ? '; targets must start with \"./\"' : ''}`\n },\n Error\n);\n\ncodes.ERR_MODULE_NOT_FOUND = createError(\n 'ERR_MODULE_NOT_FOUND',\n /**\n * @param {string} path\n * @param {string} base\n * @param {string} [type]\n */\n (path, base, type = 'package') => {\n return `Cannot find ${type} '${path}' imported from ${base}`\n },\n Error\n);\n\ncodes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(\n 'ERR_PACKAGE_IMPORT_NOT_DEFINED',\n /**\n * @param {string} specifier\n * @param {string} packagePath\n * @param {string} base\n */\n (specifier, packagePath, base) => {\n return `Package import specifier \"${specifier}\" is not defined${\n packagePath ? ` in package ${packagePath}package.json` : ''\n } imported from ${base}`\n },\n TypeError\n);\n\ncodes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(\n 'ERR_PACKAGE_PATH_NOT_EXPORTED',\n /**\n * @param {string} pkgPath\n * @param {string} subpath\n * @param {string} [base]\n */\n (pkgPath, subpath, base = undefined) => {\n if (subpath === '.')\n return `No \"exports\" main defined in ${pkgPath}package.json${\n base ? ` imported from ${base}` : ''\n }`\n return `Package subpath '${subpath}' is not defined by \"exports\" in ${pkgPath}package.json${\n base ? ` imported from ${base}` : ''\n }`\n },\n Error\n);\n\ncodes.ERR_UNSUPPORTED_DIR_IMPORT = createError(\n 'ERR_UNSUPPORTED_DIR_IMPORT',\n \"Directory import '%s' is not supported \" +\n 'resolving ES modules imported from %s',\n Error\n);\n\ncodes.ERR_UNKNOWN_FILE_EXTENSION = createError(\n 'ERR_UNKNOWN_FILE_EXTENSION',\n 'Unknown file extension \"%s\" for %s',\n TypeError\n);\n\ncodes.ERR_INVALID_ARG_VALUE = createError(\n 'ERR_INVALID_ARG_VALUE',\n /**\n * @param {string} name\n * @param {unknown} value\n * @param {string} [reason='is invalid']\n */\n (name, value, reason = 'is invalid') => {\n let inspected = inspect(value);\n\n if (inspected.length > 128) {\n inspected = `${inspected.slice(0, 128)}...`;\n }\n\n const type = name.includes('.') ? 'property' : 'argument';\n\n return `The ${type} '${name}' ${reason}. Received ${inspected}`\n },\n TypeError\n // Note: extra classes have been shaken out.\n // , RangeError\n);\n\ncodes.ERR_UNSUPPORTED_ESM_URL_SCHEME = createError(\n 'ERR_UNSUPPORTED_ESM_URL_SCHEME',\n /**\n * @param {URL} url\n */\n (url) => {\n let message =\n 'Only file and data URLs are supported by the default ESM loader';\n\n if (isWindows && url.protocol.length === 2) {\n message += '. On Windows, absolute paths must be valid file:// URLs';\n }\n\n message += `. Received protocol '${url.protocol}'`;\n return message\n },\n Error\n);\n\n/**\n * Utility function for registering the error codes. Only used here. Exported\n * *only* to allow for testing.\n * @param {string} sym\n * @param {MessageFunction|string} value\n * @param {ErrorConstructor} def\n * @returns {new (...args: unknown[]) => Error}\n */\nfunction createError(sym, value, def) {\n // Special case for SystemError that formats the error message differently\n // The SystemErrors only have SystemError as their base classes.\n messages.set(sym, value);\n\n return makeNodeErrorWithCode(def, sym)\n}\n\n/**\n * @param {ErrorConstructor} Base\n * @param {string} key\n * @returns {ErrorConstructor}\n */\nfunction makeNodeErrorWithCode(Base, key) {\n // @ts-expect-error It’s a Node error.\n return NodeError\n /**\n * @param {unknown[]} args\n */\n function NodeError(...args) {\n const limit = Error.stackTraceLimit;\n if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;\n const error = new Base();\n // Reset the limit and setting the name property.\n if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;\n const message = getMessage(key, args, error);\n Object.defineProperty(error, 'message', {\n value: message,\n enumerable: false,\n writable: true,\n configurable: true\n });\n Object.defineProperty(error, 'toString', {\n /** @this {Error} */\n value() {\n return `${this.name} [${key}]: ${this.message}`\n },\n enumerable: false,\n writable: true,\n configurable: true\n });\n addCodeToName(error, Base.name, key);\n // @ts-expect-error It’s a Node error.\n error.code = key;\n return error\n }\n}\n\nconst addCodeToName = hideStackFrames(\n /**\n * @param {Error} error\n * @param {string} name\n * @param {string} code\n * @returns {void}\n */\n function (error, name, code) {\n // Set the stack\n error = captureLargerStackTrace(error);\n // Add the error code to the name to include it in the stack trace.\n error.name = `${name} [${code}]`;\n // Access the stack to generate the error message including the error code\n // from the name.\n error.stack; // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n if (name === 'SystemError') {\n Object.defineProperty(error, 'name', {\n value: name,\n enumerable: false,\n writable: true,\n configurable: true\n });\n } else {\n delete error.name;\n }\n }\n);\n\n/**\n * @returns {boolean}\n */\nfunction isErrorStackTraceLimitWritable() {\n const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');\n if (desc === undefined) {\n return Object.isExtensible(Error)\n }\n\n return own$1.call(desc, 'writable') ? desc.writable : desc.set !== undefined\n}\n\n/**\n * This function removes unnecessary frames from Node.js core errors.\n * @template {(...args: unknown[]) => unknown} T\n * @type {(fn: T) => T}\n */\nfunction hideStackFrames(fn) {\n // We rename the functions that will be hidden to cut off the stacktrace\n // at the outermost one\n const hidden = nodeInternalPrefix + fn.name;\n Object.defineProperty(fn, 'name', {value: hidden});\n return fn\n}\n\nconst captureLargerStackTrace = hideStackFrames(\n /**\n * @param {Error} error\n * @returns {Error}\n */\n function (error) {\n const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();\n if (stackTraceLimitIsWritable) {\n userStackTraceLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = Number.POSITIVE_INFINITY;\n }\n\n Error.captureStackTrace(error);\n\n // Reset the limit\n if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;\n\n return error\n }\n);\n\n/**\n * @param {string} key\n * @param {unknown[]} args\n * @param {Error} self\n * @returns {string}\n */\nfunction getMessage(key, args, self) {\n const message = messages.get(key);\n\n if (typeof message === 'function') {\n assert(\n message.length <= args.length, // Default options do not count.\n `Code: ${key}; The provided arguments length (${args.length}) does not ` +\n `match the required ones (${message.length}).`\n );\n return Reflect.apply(message, self, args)\n }\n\n const expectedLength = (message.match(/%[dfijoOs]/g) || []).length;\n assert(\n expectedLength === args.length,\n `Code: ${key}; The provided arguments length (${args.length}) does not ` +\n `match the required ones (${expectedLength}).`\n );\n if (args.length === 0) return message\n\n args.unshift(message);\n return Reflect.apply(format, null, args)\n}\n\n// Manually “tree shaken” from:\n\nconst {ERR_UNKNOWN_FILE_EXTENSION} = codes;\n\nconst extensionFormatMap = {\n __proto__: null,\n '.cjs': 'commonjs',\n '.js': 'module',\n '.mjs': 'module'\n};\n\n/**\n * @param {string} url\n * @returns {{format: string|null}}\n */\nfunction defaultGetFormat(url) {\n if (url.startsWith('node:')) {\n return {format: 'builtin'}\n }\n\n const parsed = new URL(url);\n\n if (parsed.protocol === 'data:') {\n const {1: mime} = /^([^/]+\\/[^;,]+)[^,]*?(;base64)?,/.exec(\n parsed.pathname\n ) || [null, null];\n const format = mime === 'text/javascript' ? 'module' : null;\n return {format}\n }\n\n if (parsed.protocol === 'file:') {\n const ext = path.extname(parsed.pathname);\n /** @type {string} */\n let format;\n if (ext === '.js') {\n format = getPackageType(parsed.href) === 'module' ? 'module' : 'commonjs';\n } else {\n format = extensionFormatMap[ext];\n }\n\n if (!format) {\n throw new ERR_UNKNOWN_FILE_EXTENSION(ext, fileURLToPath(url))\n }\n\n return {format: format || null}\n }\n\n return {format: null}\n}\n\n// Manually “tree shaken” from:\n\nconst listOfBuiltins = builtins();\n\nconst {\n ERR_INVALID_MODULE_SPECIFIER,\n ERR_INVALID_PACKAGE_CONFIG,\n ERR_INVALID_PACKAGE_TARGET,\n ERR_MODULE_NOT_FOUND,\n ERR_PACKAGE_IMPORT_NOT_DEFINED,\n ERR_PACKAGE_PATH_NOT_EXPORTED,\n ERR_UNSUPPORTED_DIR_IMPORT,\n ERR_UNSUPPORTED_ESM_URL_SCHEME,\n ERR_INVALID_ARG_VALUE\n} = codes;\n\nconst own = {}.hasOwnProperty;\n\nconst DEFAULT_CONDITIONS = Object.freeze(['node', 'import']);\nconst DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS);\n\nconst invalidSegmentRegEx = /(^|\\\\|\\/)(\\.\\.?|node_modules)(\\\\|\\/|$)/;\nconst patternRegEx = /\\*/g;\nconst encodedSepRegEx = /%2f|%2c/i;\n/** @type {Set} */\nconst emittedPackageWarnings = new Set();\n/** @type {Map} */\nconst packageJsonCache = new Map();\n\n/**\n * @param {string} match\n * @param {URL} pjsonUrl\n * @param {boolean} isExports\n * @param {URL} base\n * @returns {void}\n */\nfunction emitFolderMapDeprecation(match, pjsonUrl, isExports, base) {\n const pjsonPath = fileURLToPath(pjsonUrl);\n\n if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return\n emittedPackageWarnings.add(pjsonPath + '|' + match);\n process.emitWarning(\n `Use of deprecated folder mapping \"${match}\" in the ${\n isExports ? '\"exports\"' : '\"imports\"'\n } field module resolution of the package at ${pjsonPath}${\n base ? ` imported from ${fileURLToPath(base)}` : ''\n }.\\n` +\n `Update this package.json to use a subpath pattern like \"${match}*\".`,\n 'DeprecationWarning',\n 'DEP0148'\n );\n}\n\n/**\n * @param {URL} url\n * @param {URL} packageJsonUrl\n * @param {URL} base\n * @param {unknown} [main]\n * @returns {void}\n */\nfunction emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {\n const {format} = defaultGetFormat(url.href);\n if (format !== 'module') return\n const path = fileURLToPath(url.href);\n const pkgPath = fileURLToPath(new URL('.', packageJsonUrl));\n const basePath = fileURLToPath(base);\n if (main)\n process.emitWarning(\n `Package ${pkgPath} has a \"main\" field set to ${JSON.stringify(main)}, ` +\n `excluding the full filename and extension to the resolved file at \"${path.slice(\n pkgPath.length\n )}\", imported from ${basePath}.\\n Automatic extension resolution of the \"main\" field is` +\n 'deprecated for ES modules.',\n 'DeprecationWarning',\n 'DEP0151'\n );\n else\n process.emitWarning(\n `No \"main\" or \"exports\" field defined in the package.json for ${pkgPath} resolving the main entry point \"${path.slice(\n pkgPath.length\n )}\", imported from ${basePath}.\\nDefault \"index\" lookups for the main are deprecated for ES modules.`,\n 'DeprecationWarning',\n 'DEP0151'\n );\n}\n\n/**\n * @param {string[]} [conditions]\n * @returns {Set}\n */\nfunction getConditionsSet(conditions) {\n if (conditions !== undefined && conditions !== DEFAULT_CONDITIONS) {\n if (!Array.isArray(conditions)) {\n throw new ERR_INVALID_ARG_VALUE(\n 'conditions',\n conditions,\n 'expected an array'\n )\n }\n\n return new Set(conditions)\n }\n\n return DEFAULT_CONDITIONS_SET\n}\n\n/**\n * @param {string} path\n * @returns {Stats}\n */\nfunction tryStatSync(path) {\n // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.\n try {\n return statSync(path)\n } catch {\n return new Stats()\n }\n}\n\n/**\n * @param {string} path\n * @param {string|URL} specifier Note: `specifier` is actually optional, not base.\n * @param {URL} [base]\n * @returns {PackageConfig}\n */\nfunction getPackageConfig(path, specifier, base) {\n const existing = packageJsonCache.get(path);\n if (existing !== undefined) {\n return existing\n }\n\n const source = reader.read(path).string;\n\n if (source === undefined) {\n /** @type {PackageConfig} */\n const packageConfig = {\n pjsonPath: path,\n exists: false,\n main: undefined,\n name: undefined,\n type: 'none',\n exports: undefined,\n imports: undefined\n };\n packageJsonCache.set(path, packageConfig);\n return packageConfig\n }\n\n /** @type {Object.} */\n let packageJson;\n try {\n packageJson = JSON.parse(source);\n } catch (error) {\n throw new ERR_INVALID_PACKAGE_CONFIG(\n path,\n (base ? `\"${specifier}\" from ` : '') + fileURLToPath(base || specifier),\n error.message\n )\n }\n\n const {exports, imports, main, name, type} = packageJson;\n\n /** @type {PackageConfig} */\n const packageConfig = {\n pjsonPath: path,\n exists: true,\n main: typeof main === 'string' ? main : undefined,\n name: typeof name === 'string' ? name : undefined,\n type: type === 'module' || type === 'commonjs' ? type : 'none',\n // @ts-expect-error Assume `Object.`.\n exports,\n // @ts-expect-error Assume `Object.`.\n imports: imports && typeof imports === 'object' ? imports : undefined\n };\n packageJsonCache.set(path, packageConfig);\n return packageConfig\n}\n\n/**\n * @param {URL|string} resolved\n * @returns {PackageConfig}\n */\nfunction getPackageScopeConfig(resolved) {\n let packageJsonUrl = new URL('./package.json', resolved);\n\n while (true) {\n const packageJsonPath = packageJsonUrl.pathname;\n\n if (packageJsonPath.endsWith('node_modules/package.json')) break\n\n const packageConfig = getPackageConfig(\n fileURLToPath(packageJsonUrl),\n resolved\n );\n if (packageConfig.exists) return packageConfig\n\n const lastPackageJsonUrl = packageJsonUrl;\n packageJsonUrl = new URL('../package.json', packageJsonUrl);\n\n // Terminates at root where ../package.json equals ../../package.json\n // (can't just check \"/package.json\" for Windows support).\n if (packageJsonUrl.pathname === lastPackageJsonUrl.pathname) break\n }\n\n const packageJsonPath = fileURLToPath(packageJsonUrl);\n /** @type {PackageConfig} */\n const packageConfig = {\n pjsonPath: packageJsonPath,\n exists: false,\n main: undefined,\n name: undefined,\n type: 'none',\n exports: undefined,\n imports: undefined\n };\n packageJsonCache.set(packageJsonPath, packageConfig);\n return packageConfig\n}\n\n/**\n * Legacy CommonJS main resolution:\n * 1. let M = pkg_url + (json main field)\n * 2. TRY(M, M.js, M.json, M.node)\n * 3. TRY(M/index.js, M/index.json, M/index.node)\n * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)\n * 5. NOT_FOUND\n *\n * @param {URL} url\n * @returns {boolean}\n */\nfunction fileExists(url) {\n return tryStatSync(fileURLToPath(url)).isFile()\n}\n\n/**\n * @param {URL} packageJsonUrl\n * @param {PackageConfig} packageConfig\n * @param {URL} base\n * @returns {URL}\n */\nfunction legacyMainResolve(packageJsonUrl, packageConfig, base) {\n /** @type {URL} */\n let guess;\n if (packageConfig.main !== undefined) {\n guess = new URL(`./${packageConfig.main}`, packageJsonUrl);\n // Note: fs check redundances will be handled by Descriptor cache here.\n if (fileExists(guess)) return guess\n\n const tries = [\n `./${packageConfig.main}.js`,\n `./${packageConfig.main}.json`,\n `./${packageConfig.main}.node`,\n `./${packageConfig.main}/index.js`,\n `./${packageConfig.main}/index.json`,\n `./${packageConfig.main}/index.node`\n ];\n let i = -1;\n\n while (++i < tries.length) {\n guess = new URL(tries[i], packageJsonUrl);\n if (fileExists(guess)) break\n guess = undefined;\n }\n\n if (guess) {\n emitLegacyIndexDeprecation(\n guess,\n packageJsonUrl,\n base,\n packageConfig.main\n );\n return guess\n }\n // Fallthrough.\n }\n\n const tries = ['./index.js', './index.json', './index.node'];\n let i = -1;\n\n while (++i < tries.length) {\n guess = new URL(tries[i], packageJsonUrl);\n if (fileExists(guess)) break\n guess = undefined;\n }\n\n if (guess) {\n emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);\n return guess\n }\n\n // Not found.\n throw new ERR_MODULE_NOT_FOUND(\n fileURLToPath(new URL('.', packageJsonUrl)),\n fileURLToPath(base)\n )\n}\n\n/**\n * @param {URL} resolved\n * @param {URL} base\n * @returns {URL}\n */\nfunction finalizeResolution(resolved, base) {\n if (encodedSepRegEx.test(resolved.pathname))\n throw new ERR_INVALID_MODULE_SPECIFIER(\n resolved.pathname,\n 'must not include encoded \"/\" or \"\\\\\" characters',\n fileURLToPath(base)\n )\n\n const path = fileURLToPath(resolved);\n\n const stats = tryStatSync(path.endsWith('/') ? path.slice(-1) : path);\n\n if (stats.isDirectory()) {\n const error = new ERR_UNSUPPORTED_DIR_IMPORT(path, fileURLToPath(base));\n // @ts-expect-error Add this for `import.meta.resolve`.\n error.url = String(resolved);\n throw error\n }\n\n if (!stats.isFile()) {\n throw new ERR_MODULE_NOT_FOUND(\n path || resolved.pathname,\n base && fileURLToPath(base),\n 'module'\n )\n }\n\n return resolved\n}\n\n/**\n * @param {string} specifier\n * @param {URL?} packageJsonUrl\n * @param {URL} base\n * @returns {never}\n */\nfunction throwImportNotDefined(specifier, packageJsonUrl, base) {\n throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(\n specifier,\n packageJsonUrl && fileURLToPath(new URL('.', packageJsonUrl)),\n fileURLToPath(base)\n )\n}\n\n/**\n * @param {string} subpath\n * @param {URL} packageJsonUrl\n * @param {URL} base\n * @returns {never}\n */\nfunction throwExportsNotFound(subpath, packageJsonUrl, base) {\n throw new ERR_PACKAGE_PATH_NOT_EXPORTED(\n fileURLToPath(new URL('.', packageJsonUrl)),\n subpath,\n base && fileURLToPath(base)\n )\n}\n\n/**\n * @param {string} subpath\n * @param {URL} packageJsonUrl\n * @param {boolean} internal\n * @param {URL} [base]\n * @returns {never}\n */\nfunction throwInvalidSubpath(subpath, packageJsonUrl, internal, base) {\n const reason = `request is not a valid subpath for the \"${\n internal ? 'imports' : 'exports'\n }\" resolution of ${fileURLToPath(packageJsonUrl)}`;\n\n throw new ERR_INVALID_MODULE_SPECIFIER(\n subpath,\n reason,\n base && fileURLToPath(base)\n )\n}\n\n/**\n * @param {string} subpath\n * @param {unknown} target\n * @param {URL} packageJsonUrl\n * @param {boolean} internal\n * @param {URL} [base]\n * @returns {never}\n */\nfunction throwInvalidPackageTarget(\n subpath,\n target,\n packageJsonUrl,\n internal,\n base\n) {\n target =\n typeof target === 'object' && target !== null\n ? JSON.stringify(target, null, '')\n : `${target}`;\n\n throw new ERR_INVALID_PACKAGE_TARGET(\n fileURLToPath(new URL('.', packageJsonUrl)),\n subpath,\n target,\n internal,\n base && fileURLToPath(base)\n )\n}\n\n/**\n * @param {string} target\n * @param {string} subpath\n * @param {string} match\n * @param {URL} packageJsonUrl\n * @param {URL} base\n * @param {boolean} pattern\n * @param {boolean} internal\n * @param {Set} conditions\n * @returns {URL}\n */\nfunction resolvePackageTargetString(\n target,\n subpath,\n match,\n packageJsonUrl,\n base,\n pattern,\n internal,\n conditions\n) {\n if (subpath !== '' && !pattern && target[target.length - 1] !== '/')\n throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);\n\n if (!target.startsWith('./')) {\n if (internal && !target.startsWith('../') && !target.startsWith('/')) {\n let isURL = false;\n\n try {\n new URL(target);\n isURL = true;\n } catch {}\n\n if (!isURL) {\n const exportTarget = pattern\n ? target.replace(patternRegEx, subpath)\n : target + subpath;\n\n return packageResolve(exportTarget, packageJsonUrl, conditions)\n }\n }\n\n throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);\n }\n\n if (invalidSegmentRegEx.test(target.slice(2)))\n throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);\n\n const resolved = new URL(target, packageJsonUrl);\n const resolvedPath = resolved.pathname;\n const packagePath = new URL('.', packageJsonUrl).pathname;\n\n if (!resolvedPath.startsWith(packagePath))\n throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);\n\n if (subpath === '') return resolved\n\n if (invalidSegmentRegEx.test(subpath))\n throwInvalidSubpath(match + subpath, packageJsonUrl, internal, base);\n\n if (pattern) return new URL(resolved.href.replace(patternRegEx, subpath))\n return new URL(subpath, resolved)\n}\n\n/**\n * @param {string} key\n * @returns {boolean}\n */\nfunction isArrayIndex(key) {\n const keyNumber = Number(key);\n if (`${keyNumber}` !== key) return false\n return keyNumber >= 0 && keyNumber < 0xffff_ffff\n}\n\n/**\n * @param {URL} packageJsonUrl\n * @param {unknown} target\n * @param {string} subpath\n * @param {string} packageSubpath\n * @param {URL} base\n * @param {boolean} pattern\n * @param {boolean} internal\n * @param {Set} conditions\n * @returns {URL}\n */\nfunction resolvePackageTarget(\n packageJsonUrl,\n target,\n subpath,\n packageSubpath,\n base,\n pattern,\n internal,\n conditions\n) {\n if (typeof target === 'string') {\n return resolvePackageTargetString(\n target,\n subpath,\n packageSubpath,\n packageJsonUrl,\n base,\n pattern,\n internal,\n conditions\n )\n }\n\n if (Array.isArray(target)) {\n /** @type {unknown[]} */\n const targetList = target;\n if (targetList.length === 0) return null\n\n /** @type {Error} */\n let lastException;\n let i = -1;\n\n while (++i < targetList.length) {\n const targetItem = targetList[i];\n /** @type {URL} */\n let resolved;\n try {\n resolved = resolvePackageTarget(\n packageJsonUrl,\n targetItem,\n subpath,\n packageSubpath,\n base,\n pattern,\n internal,\n conditions\n );\n } catch (error) {\n lastException = error;\n if (error.code === 'ERR_INVALID_PACKAGE_TARGET') continue\n throw error\n }\n\n if (resolved === undefined) continue\n\n if (resolved === null) {\n lastException = null;\n continue\n }\n\n return resolved\n }\n\n if (lastException === undefined || lastException === null) {\n // @ts-expect-error The diff between `undefined` and `null` seems to be\n // intentional\n return lastException\n }\n\n throw lastException\n }\n\n if (typeof target === 'object' && target !== null) {\n const keys = Object.getOwnPropertyNames(target);\n let i = -1;\n\n while (++i < keys.length) {\n const key = keys[i];\n if (isArrayIndex(key)) {\n throw new ERR_INVALID_PACKAGE_CONFIG(\n fileURLToPath(packageJsonUrl),\n base,\n '\"exports\" cannot contain numeric property keys.'\n )\n }\n }\n\n i = -1;\n\n while (++i < keys.length) {\n const key = keys[i];\n if (key === 'default' || (conditions && conditions.has(key))) {\n /** @type {unknown} */\n const conditionalTarget = target[key];\n const resolved = resolvePackageTarget(\n packageJsonUrl,\n conditionalTarget,\n subpath,\n packageSubpath,\n base,\n pattern,\n internal,\n conditions\n );\n if (resolved === undefined) continue\n return resolved\n }\n }\n\n return undefined\n }\n\n if (target === null) {\n return null\n }\n\n throwInvalidPackageTarget(\n packageSubpath,\n target,\n packageJsonUrl,\n internal,\n base\n );\n}\n\n/**\n * @param {unknown} exports\n * @param {URL} packageJsonUrl\n * @param {URL} base\n * @returns {boolean}\n */\nfunction isConditionalExportsMainSugar(exports, packageJsonUrl, base) {\n if (typeof exports === 'string' || Array.isArray(exports)) return true\n if (typeof exports !== 'object' || exports === null) return false\n\n const keys = Object.getOwnPropertyNames(exports);\n let isConditionalSugar = false;\n let i = 0;\n let j = -1;\n while (++j < keys.length) {\n const key = keys[j];\n const curIsConditionalSugar = key === '' || key[0] !== '.';\n if (i++ === 0) {\n isConditionalSugar = curIsConditionalSugar;\n } else if (isConditionalSugar !== curIsConditionalSugar) {\n throw new ERR_INVALID_PACKAGE_CONFIG(\n fileURLToPath(packageJsonUrl),\n base,\n '\"exports\" cannot contain some keys starting with \\'.\\' and some not.' +\n ' The exports object must either be an object of package subpath keys' +\n ' or an object of main entry condition name keys only.'\n )\n }\n }\n\n return isConditionalSugar\n}\n\n/**\n * @param {URL} packageJsonUrl\n * @param {string} packageSubpath\n * @param {Object.} packageConfig\n * @param {URL} base\n * @param {Set} conditions\n * @returns {ResolveObject}\n */\nfunction packageExportsResolve(\n packageJsonUrl,\n packageSubpath,\n packageConfig,\n base,\n conditions\n) {\n let exports = packageConfig.exports;\n if (isConditionalExportsMainSugar(exports, packageJsonUrl, base))\n exports = {'.': exports};\n\n if (own.call(exports, packageSubpath)) {\n const target = exports[packageSubpath];\n const resolved = resolvePackageTarget(\n packageJsonUrl,\n target,\n '',\n packageSubpath,\n base,\n false,\n false,\n conditions\n );\n if (resolved === null || resolved === undefined)\n throwExportsNotFound(packageSubpath, packageJsonUrl, base);\n return {resolved, exact: true}\n }\n\n let bestMatch = '';\n const keys = Object.getOwnPropertyNames(exports);\n let i = -1;\n\n while (++i < keys.length) {\n const key = keys[i];\n if (\n key[key.length - 1] === '*' &&\n packageSubpath.startsWith(key.slice(0, -1)) &&\n packageSubpath.length >= key.length &&\n key.length > bestMatch.length\n ) {\n bestMatch = key;\n } else if (\n key[key.length - 1] === '/' &&\n packageSubpath.startsWith(key) &&\n key.length > bestMatch.length\n ) {\n bestMatch = key;\n }\n }\n\n if (bestMatch) {\n const target = exports[bestMatch];\n const pattern = bestMatch[bestMatch.length - 1] === '*';\n const subpath = packageSubpath.slice(bestMatch.length - (pattern ? 1 : 0));\n const resolved = resolvePackageTarget(\n packageJsonUrl,\n target,\n subpath,\n bestMatch,\n base,\n pattern,\n false,\n conditions\n );\n if (resolved === null || resolved === undefined)\n throwExportsNotFound(packageSubpath, packageJsonUrl, base);\n if (!pattern)\n emitFolderMapDeprecation(bestMatch, packageJsonUrl, true, base);\n return {resolved, exact: pattern}\n }\n\n throwExportsNotFound(packageSubpath, packageJsonUrl, base);\n}\n\n/**\n * @param {string} name\n * @param {URL} base\n * @param {Set} [conditions]\n * @returns {ResolveObject}\n */\nfunction packageImportsResolve(name, base, conditions) {\n if (name === '#' || name.startsWith('#/')) {\n const reason = 'is not a valid internal imports specifier name';\n throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath(base))\n }\n\n /** @type {URL} */\n let packageJsonUrl;\n\n const packageConfig = getPackageScopeConfig(base);\n\n if (packageConfig.exists) {\n packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);\n const imports = packageConfig.imports;\n if (imports) {\n if (own.call(imports, name)) {\n const resolved = resolvePackageTarget(\n packageJsonUrl,\n imports[name],\n '',\n name,\n base,\n false,\n true,\n conditions\n );\n if (resolved !== null) return {resolved, exact: true}\n } else {\n let bestMatch = '';\n const keys = Object.getOwnPropertyNames(imports);\n let i = -1;\n\n while (++i < keys.length) {\n const key = keys[i];\n\n if (\n key[key.length - 1] === '*' &&\n name.startsWith(key.slice(0, -1)) &&\n name.length >= key.length &&\n key.length > bestMatch.length\n ) {\n bestMatch = key;\n } else if (\n key[key.length - 1] === '/' &&\n name.startsWith(key) &&\n key.length > bestMatch.length\n ) {\n bestMatch = key;\n }\n }\n\n if (bestMatch) {\n const target = imports[bestMatch];\n const pattern = bestMatch[bestMatch.length - 1] === '*';\n const subpath = name.slice(bestMatch.length - (pattern ? 1 : 0));\n const resolved = resolvePackageTarget(\n packageJsonUrl,\n target,\n subpath,\n bestMatch,\n base,\n pattern,\n true,\n conditions\n );\n if (resolved !== null) {\n if (!pattern)\n emitFolderMapDeprecation(bestMatch, packageJsonUrl, false, base);\n return {resolved, exact: pattern}\n }\n }\n }\n }\n }\n\n throwImportNotDefined(name, packageJsonUrl, base);\n}\n\n/**\n * @param {string} url\n * @returns {PackageType}\n */\nfunction getPackageType(url) {\n const packageConfig = getPackageScopeConfig(url);\n return packageConfig.type\n}\n\n/**\n * @param {string} specifier\n * @param {URL} base\n */\nfunction parsePackageName(specifier, base) {\n let separatorIndex = specifier.indexOf('/');\n let validPackageName = true;\n let isScoped = false;\n if (specifier[0] === '@') {\n isScoped = true;\n if (separatorIndex === -1 || specifier.length === 0) {\n validPackageName = false;\n } else {\n separatorIndex = specifier.indexOf('/', separatorIndex + 1);\n }\n }\n\n const packageName =\n separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);\n\n // Package name cannot have leading . and cannot have percent-encoding or\n // separators.\n let i = -1;\n while (++i < packageName.length) {\n if (packageName[i] === '%' || packageName[i] === '\\\\') {\n validPackageName = false;\n break\n }\n }\n\n if (!validPackageName) {\n throw new ERR_INVALID_MODULE_SPECIFIER(\n specifier,\n 'is not a valid package name',\n fileURLToPath(base)\n )\n }\n\n const packageSubpath =\n '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));\n\n return {packageName, packageSubpath, isScoped}\n}\n\n/**\n * @param {string} specifier\n * @param {URL} base\n * @param {Set} conditions\n * @returns {URL}\n */\nfunction packageResolve(specifier, base, conditions) {\n const {packageName, packageSubpath, isScoped} = parsePackageName(\n specifier,\n base\n );\n\n // ResolveSelf\n const packageConfig = getPackageScopeConfig(base);\n\n // Can’t test.\n /* c8 ignore next 16 */\n if (packageConfig.exists) {\n const packageJsonUrl = pathToFileURL(packageConfig.pjsonPath);\n if (\n packageConfig.name === packageName &&\n packageConfig.exports !== undefined &&\n packageConfig.exports !== null\n ) {\n return packageExportsResolve(\n packageJsonUrl,\n packageSubpath,\n packageConfig,\n base,\n conditions\n ).resolved\n }\n }\n\n let packageJsonUrl = new URL(\n './node_modules/' + packageName + '/package.json',\n base\n );\n let packageJsonPath = fileURLToPath(packageJsonUrl);\n /** @type {string} */\n let lastPath;\n do {\n const stat = tryStatSync(packageJsonPath.slice(0, -13));\n if (!stat.isDirectory()) {\n lastPath = packageJsonPath;\n packageJsonUrl = new URL(\n (isScoped ? '../../../../node_modules/' : '../../../node_modules/') +\n packageName +\n '/package.json',\n packageJsonUrl\n );\n packageJsonPath = fileURLToPath(packageJsonUrl);\n continue\n }\n\n // Package match.\n const packageConfig = getPackageConfig(packageJsonPath, specifier, base);\n if (packageConfig.exports !== undefined && packageConfig.exports !== null)\n return packageExportsResolve(\n packageJsonUrl,\n packageSubpath,\n packageConfig,\n base,\n conditions\n ).resolved\n if (packageSubpath === '.')\n return legacyMainResolve(packageJsonUrl, packageConfig, base)\n return new URL(packageSubpath, packageJsonUrl)\n // Cross-platform root check.\n } while (packageJsonPath.length !== lastPath.length)\n\n throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base))\n}\n\n/**\n * @param {string} specifier\n * @returns {boolean}\n */\nfunction isRelativeSpecifier(specifier) {\n if (specifier[0] === '.') {\n if (specifier.length === 1 || specifier[1] === '/') return true\n if (\n specifier[1] === '.' &&\n (specifier.length === 2 || specifier[2] === '/')\n ) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * @param {string} specifier\n * @returns {boolean}\n */\nfunction shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {\n if (specifier === '') return false\n if (specifier[0] === '/') return true\n return isRelativeSpecifier(specifier)\n}\n\n/**\n * The “Resolver Algorithm Specification” as detailed in the Node docs (which is\n * sync and slightly lower-level than `resolve`).\n *\n *\n *\n * @param {string} specifier\n * @param {URL} base\n * @param {Set} [conditions]\n * @returns {URL}\n */\nfunction moduleResolve(specifier, base, conditions) {\n // Order swapped from spec for minor perf gain.\n // Ok since relative URLs cannot parse as URLs.\n /** @type {URL} */\n let resolved;\n\n if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {\n resolved = new URL(specifier, base);\n } else if (specifier[0] === '#') {\n({resolved} = packageImportsResolve(specifier, base, conditions));\n } else {\n try {\n resolved = new URL(specifier);\n } catch {\n resolved = packageResolve(specifier, base, conditions);\n }\n }\n\n return finalizeResolution(resolved, base)\n}\n\n/**\n * @param {string} specifier\n * @param {{parentURL?: string, conditions?: string[]}} context\n * @returns {{url: string}}\n */\nfunction defaultResolve(specifier, context = {}) {\n const {parentURL} = context;\n /** @type {URL} */\n let parsed;\n\n try {\n parsed = new URL(specifier);\n if (parsed.protocol === 'data:') {\n return {url: specifier}\n }\n } catch {}\n\n if (parsed && parsed.protocol === 'node:') return {url: specifier}\n if (parsed && parsed.protocol !== 'file:' && parsed.protocol !== 'data:')\n throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(parsed)\n\n if (listOfBuiltins.includes(specifier)) {\n return {url: 'node:' + specifier}\n }\n\n if (parentURL.startsWith('data:')) {\n // This is gonna blow up, we want the error\n new URL(specifier, parentURL);\n }\n\n const conditions = getConditionsSet(context.conditions);\n let url = moduleResolve(specifier, new URL(parentURL), conditions);\n\n const urlPath = fileURLToPath(url);\n const real = realpathSync(urlPath);\n const old = url;\n url = pathToFileURL(real + (urlPath.endsWith(path.sep) ? '/' : ''));\n url.search = old.search;\n url.hash = old.hash;\n\n return {url: `${url}`}\n}\n\n/**\n * Provides a module-relative resolution function scoped to each module,\n * returning the URL string.\n * `import.meta.resolve` also accepts a second argument which is the parent\n * module from which to resolve from.\n *\n * This function is asynchronous because the ES module resolver in Node.js is\n * allowed to be asynchronous.\n *\n * @param {string} specifier The module specifier to resolve relative to parent.\n * @param {string} parent The absolute parent module URL to resolve from.\n * You should pass `import.meta.url` or something else\n * @returns {Promise}\n */\nasync function resolve(specifier, parent) {\n if (!parent) {\n throw new Error(\n 'Please pass `parent`: `import-meta-resolve` cannot ponyfill that'\n )\n }\n\n try {\n return defaultResolve(specifier, {parentURL: parent}).url\n } catch (error) {\n return error.code === 'ERR_UNSUPPORTED_DIR_IMPORT'\n ? error.url\n : Promise.reject(error)\n }\n}\n\nexport { moduleResolve, resolve };\n"],"mappings":";;;;;;;;AAoFA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;AACA;EAAA;;EAAA;IAAA;EAAA;;EAAA;AAAA;;;;;;;;;;AAEA,IAAIA,IAAI,GAAG;EAACC,OAAO,EAAE;AAAV,CAAX;AAIA,MAAMC,mBAAmB,GAAG,OAA5B;AAEA,MAAMC,YAAY,GAAG,GAArB;AACA,MAAMC,kBAAkB,GAAGC,MAAM,CAACC,gBAAP,IACA,gBAD3B;AAIA,MAAMC,yBAAyB,GAAG,EAAlC;AAEA,IAAIC,SAAS,GAAG;EACdN,mBADc;EAEdO,UAAU,EAAEN,YAFE;EAGdG,gBAAgB,EAAEF,kBAHJ;EAIdG;AAJc,CAAhB;AAOA,MAAMG,OAAO,GACX,OAAOC,OAAP,KAAmB,QAAnB,IACAA,OAAO,CAACC,GADR,IAEAD,OAAO,CAACC,GAAR,CAAYC,UAFZ,IAGA,cAAcC,IAAd,CAAmBH,OAAO,CAACC,GAAR,CAAYC,UAA/B,CAJc,GAKZ,CAAC,GAAGE,IAAJ,KAAaC,OAAO,CAACC,KAAR,CAAc,QAAd,EAAwB,GAAGF,IAA3B,CALD,GAMZ,MAAM,CAAE,CANZ;AAQA,IAAIG,OAAO,GAAGR,OAAd;;AAEC,WAAUS,MAAV,EAAkBlB,OAAlB,EAA2B;EAC3B,MAAM;IAAEM;EAAF,IAAgCC,SAAtC;EACA,MAAMY,KAAK,GAAGF,OAAd;EACAjB,OAAO,GAAGkB,MAAM,CAAClB,OAAP,GAA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AAC,kBAAA,EAAaF,OAAb,CAAb;EACA,MAAMG,GAAG,GAAGnI,GAAZ;EACAA,GAAG,GAAG,IAAAiH,oBAAA,EAAcgB,IAAI,IAAID,OAAO,CAACrD,QAAR,CAAiB1H,OAAA,CAAKmL,GAAtB,IAA6B,GAA7B,GAAmC,EAAvC,CAAlB,CAAN;EACApI,GAAG,CAACqI,MAAJ,GAAaF,GAAG,CAACE,MAAjB;EACArI,GAAG,CAACsI,IAAJ,GAAWH,GAAG,CAACG,IAAf;EAEA,OAAO;IAACtI,GAAG,EAAG,GAAEA,GAAI;EAAb,CAAP;AACD;;SAgBcuI,O;;;;;+BAAf,WAAuBlJ,SAAvB,EAAkC5B,MAAlC,EAA0C;IACxC,IAAI,CAACA,MAAL,EAAa;MACX,MAAM,IAAI9Z,KAAJ,CACJ,kEADI,CAAN;IAGD;;IAED,IAAI;MACF,OAAOkkB,cAAc,CAACxI,SAAD,EAAY;QAAC0I,SAAS,EAAEtK;MAAZ,CAAZ,CAAd,CAA+CuC,GAAtD;IACD,CAFD,CAEE,OAAOriB,KAAP,EAAc;MACd,OAAOA,KAAK,CAAC6f,IAAN,KAAe,4BAAf,GACH7f,KAAK,CAACqiB,GADH,GAEHwI,OAAO,CAACC,MAAR,CAAe9qB,KAAf,CAFJ;IAGD;EACF,C"} \ No newline at end of file diff --git a/node_modules/@babel/core/package.json b/node_modules/@babel/core/package.json new file mode 100644 index 0000000..12a2f65 --- /dev/null +++ b/node_modules/@babel/core/package.json @@ -0,0 +1,80 @@ +{ + "name": "@babel/core", + "version": "7.19.6", + "description": "Babel compiler core.", + "main": "./lib/index.js", + "author": "The Babel Team (https://babel.dev/team)", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "https://github.com/babel/babel.git", + "directory": "packages/babel-core" + }, + "homepage": "https://babel.dev/docs/en/next/babel-core", + "bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20core%22+is%3Aopen", + "keywords": [ + "6to5", + "babel", + "classes", + "const", + "es6", + "harmony", + "let", + "modules", + "transpile", + "transpiler", + "var", + "babel-core", + "compiler" + ], + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + }, + "browser": { + "./lib/config/files/index.js": "./lib/config/files/index-browser.js", + "./lib/config/resolve-targets.js": "./lib/config/resolve-targets-browser.js", + "./lib/transform-file.js": "./lib/transform-file-browser.js", + "./src/config/files/index.ts": "./src/config/files/index-browser.ts", + "./src/config/resolve-targets.ts": "./src/config/resolve-targets-browser.ts", + "./src/transform-file.ts": "./src/transform-file-browser.ts" + }, + "dependencies": { + "@ampproject/remapping": "^2.1.0", + "@babel/code-frame": "^7.18.6", + "@babel/generator": "^7.19.6", + "@babel/helper-compilation-targets": "^7.19.3", + "@babel/helper-module-transforms": "^7.19.6", + "@babel/helpers": "^7.19.4", + "@babel/parser": "^7.19.6", + "@babel/template": "^7.18.10", + "@babel/traverse": "^7.19.6", + "@babel/types": "^7.19.4", + "convert-source-map": "^1.7.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.1", + "semver": "^6.3.0" + }, + "devDependencies": { + "@babel/helper-transform-fixture-test-runner": "^7.19.4", + "@babel/plugin-syntax-flow": "^7.18.6", + "@babel/plugin-transform-flow-strip-types": "^7.19.0", + "@babel/plugin-transform-modules-commonjs": "^7.19.6", + "@babel/preset-env": "^7.19.4", + "@jridgewell/trace-mapping": "^0.3.8", + "@types/convert-source-map": "^1.5.1", + "@types/debug": "^4.1.0", + "@types/gensync": "^1.0.0", + "@types/resolve": "^1.3.2", + "@types/semver": "^5.4.0", + "rimraf": "^3.0.0" + }, + "type": "commonjs" +} \ No newline at end of file diff --git a/node_modules/@babel/core/src/config/files/index-browser.ts b/node_modules/@babel/core/src/config/files/index-browser.ts new file mode 100644 index 0000000..08f91f6 --- /dev/null +++ b/node_modules/@babel/core/src/config/files/index-browser.ts @@ -0,0 +1,109 @@ +import type { Handler } from "gensync"; + +import type { + ConfigFile, + IgnoreFile, + RelativeConfig, + FilePackageData, +} from "./types"; + +import type { CallerMetadata } from "../validation/options"; + +export type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData }; + +export function findConfigUpwards( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + rootDir: string, +): string | null { + return null; +} + +// eslint-disable-next-line require-yield +export function* findPackageData(filepath: string): Handler { + return { + filepath, + directories: [], + pkg: null, + isPackage: false, + }; +} + +// eslint-disable-next-line require-yield +export function* findRelativeConfig( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + pkgData: FilePackageData, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + envName: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + caller: CallerMetadata | undefined, +): Handler { + return { config: null, ignore: null }; +} + +// eslint-disable-next-line require-yield +export function* findRootConfig( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + dirname: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + envName: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + caller: CallerMetadata | undefined, +): Handler { + return null; +} + +// eslint-disable-next-line require-yield +export function* loadConfig( + name: string, + dirname: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + envName: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + caller: CallerMetadata | undefined, +): Handler { + throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`); +} + +// eslint-disable-next-line require-yield +export function* resolveShowConfigPath( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + dirname: string, +): Handler { + return null; +} + +export const ROOT_CONFIG_FILENAMES: string[] = []; + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function resolvePlugin(name: string, dirname: string): string | null { + return null; +} + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function resolvePreset(name: string, dirname: string): string | null { + return null; +} + +export function loadPlugin( + name: string, + dirname: string, +): Handler<{ + filepath: string; + value: unknown; +}> { + throw new Error( + `Cannot load plugin ${name} relative to ${dirname} in a browser`, + ); +} + +export function loadPreset( + name: string, + dirname: string, +): Handler<{ + filepath: string; + value: unknown; +}> { + throw new Error( + `Cannot load preset ${name} relative to ${dirname} in a browser`, + ); +} diff --git a/node_modules/@babel/core/src/config/files/index.ts b/node_modules/@babel/core/src/config/files/index.ts new file mode 100644 index 0000000..31e8560 --- /dev/null +++ b/node_modules/@babel/core/src/config/files/index.ts @@ -0,0 +1,30 @@ +type indexBrowserType = typeof import("./index-browser"); +type indexType = typeof import("./index"); + +// Kind of gross, but essentially asserting that the exports of this module are the same as the +// exports of index-browser, since this file may be replaced at bundle time with index-browser. +({} as any as indexBrowserType as indexType); + +export { findPackageData } from "./package"; + +export { + findConfigUpwards, + findRelativeConfig, + findRootConfig, + loadConfig, + resolveShowConfigPath, + ROOT_CONFIG_FILENAMES, +} from "./configuration"; +export type { + ConfigFile, + IgnoreFile, + RelativeConfig, + FilePackageData, +} from "./types"; +export { loadPlugin, loadPreset } from "./plugins"; + +import gensync from "gensync"; +import * as plugins from "./plugins"; + +export const resolvePlugin = gensync(plugins.resolvePlugin).sync; +export const resolvePreset = gensync(plugins.resolvePreset).sync; diff --git a/node_modules/@babel/core/src/config/resolve-targets-browser.ts b/node_modules/@babel/core/src/config/resolve-targets-browser.ts new file mode 100644 index 0000000..60745dd --- /dev/null +++ b/node_modules/@babel/core/src/config/resolve-targets-browser.ts @@ -0,0 +1,40 @@ +import type { ValidatedOptions } from "./validation/options"; +import getTargets, { + type InputTargets, +} from "@babel/helper-compilation-targets"; + +import type { Targets } from "@babel/helper-compilation-targets"; + +export function resolveBrowserslistConfigFile( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + browserslistConfigFile: string, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + configFilePath: string, +): string | void { + return undefined; +} + +export function resolveTargets( + options: ValidatedOptions, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + root: string, +): Targets { + const optTargets = options.targets; + let targets: InputTargets; + + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { browsers: optTargets }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = { ...optTargets, esmodules: "intersect" }; + } else { + // https://github.com/microsoft/TypeScript/issues/17002 + targets = optTargets as InputTargets; + } + } + + return getTargets(targets, { + ignoreBrowserslistConfig: true, + browserslistEnv: options.browserslistEnv, + }); +} diff --git a/node_modules/@babel/core/src/config/resolve-targets.ts b/node_modules/@babel/core/src/config/resolve-targets.ts new file mode 100644 index 0000000..a7d9a79 --- /dev/null +++ b/node_modules/@babel/core/src/config/resolve-targets.ts @@ -0,0 +1,56 @@ +type browserType = typeof import("./resolve-targets-browser"); +type nodeType = typeof import("./resolve-targets"); + +// Kind of gross, but essentially asserting that the exports of this module are the same as the +// exports of index-browser, since this file may be replaced at bundle time with index-browser. +({} as any as browserType as nodeType); + +import type { ValidatedOptions } from "./validation/options"; +import path from "path"; +import getTargets, { + type InputTargets, +} from "@babel/helper-compilation-targets"; + +import type { Targets } from "@babel/helper-compilation-targets"; + +export function resolveBrowserslistConfigFile( + browserslistConfigFile: string, + configFileDir: string, +): string | undefined { + return path.resolve(configFileDir, browserslistConfigFile); +} + +export function resolveTargets( + options: ValidatedOptions, + root: string, +): Targets { + const optTargets = options.targets; + let targets: InputTargets; + + if (typeof optTargets === "string" || Array.isArray(optTargets)) { + targets = { browsers: optTargets }; + } else if (optTargets) { + if ("esmodules" in optTargets) { + targets = { ...optTargets, esmodules: "intersect" }; + } else { + // https://github.com/microsoft/TypeScript/issues/17002 + targets = optTargets as InputTargets; + } + } + + const { browserslistConfigFile } = options; + let configFile; + let ignoreBrowserslistConfig = false; + if (typeof browserslistConfigFile === "string") { + configFile = browserslistConfigFile; + } else { + ignoreBrowserslistConfig = browserslistConfigFile === false; + } + + return getTargets(targets, { + ignoreBrowserslistConfig, + configFile, + configPath: root, + browserslistEnv: options.browserslistEnv, + }); +} diff --git a/node_modules/@babel/core/src/transform-file-browser.ts b/node_modules/@babel/core/src/transform-file-browser.ts new file mode 100644 index 0000000..f316cb4 --- /dev/null +++ b/node_modules/@babel/core/src/transform-file-browser.ts @@ -0,0 +1,31 @@ +// duplicated from transform-file so we do not have to import anything here +type TransformFile = { + (filename: string, callback: (error: Error, file: null) => void): void; + ( + filename: string, + opts: any, + callback: (error: Error, file: null) => void, + ): void; +}; + +export const transformFile: TransformFile = function transformFile( + filename, + opts, + callback?: (error: Error, file: null) => void, +) { + if (typeof opts === "function") { + callback = opts; + } + + callback(new Error("Transforming files is not supported in browsers"), null); +}; + +export function transformFileSync(): never { + throw new Error("Transforming files is not supported in browsers"); +} + +export function transformFileAsync() { + return Promise.reject( + new Error("Transforming files is not supported in browsers"), + ); +} diff --git a/node_modules/@babel/core/src/transform-file.ts b/node_modules/@babel/core/src/transform-file.ts new file mode 100644 index 0000000..c493425 --- /dev/null +++ b/node_modules/@babel/core/src/transform-file.ts @@ -0,0 +1,55 @@ +import gensync, { type Handler } from "gensync"; + +import loadConfig from "./config"; +import type { InputOptions, ResolvedConfig } from "./config"; +import { run } from "./transformation"; +import type { FileResult, FileResultCallback } from "./transformation"; +import * as fs from "./gensync-utils/fs"; + +type transformFileBrowserType = typeof import("./transform-file-browser"); +type transformFileType = typeof import("./transform-file"); + +// Kind of gross, but essentially asserting that the exports of this module are the same as the +// exports of transform-file-browser, since this file may be replaced at bundle time with +// transform-file-browser. +({} as any as transformFileBrowserType as transformFileType); + +const transformFileRunner = gensync(function* ( + filename: string, + opts?: InputOptions, +): Handler { + const options = { ...opts, filename }; + + const config: ResolvedConfig | null = yield* loadConfig(options); + if (config === null) return null; + + const code = yield* fs.readFile(filename, "utf8"); + return yield* run(config, code); +}); + +// @ts-expect-error TS doesn't detect that this signature is compatible +export function transformFile( + filename: string, + callback: FileResultCallback, +): void; +export function transformFile( + filename: string, + opts: InputOptions | undefined | null, + callback: FileResultCallback, +): void; +export function transformFile( + ...args: Parameters +) { + return transformFileRunner.errback(...args); +} + +export function transformFileSync( + ...args: Parameters +) { + return transformFileRunner.sync(...args); +} +export function transformFileAsync( + ...args: Parameters +) { + return transformFileRunner.async(...args); +} diff --git a/node_modules/@babel/generator/LICENSE b/node_modules/@babel/generator/LICENSE new file mode 100644 index 0000000..f31575e --- /dev/null +++ b/node_modules/@babel/generator/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/generator/README.md b/node_modules/@babel/generator/README.md new file mode 100644 index 0000000..b760238 --- /dev/null +++ b/node_modules/@babel/generator/README.md @@ -0,0 +1,19 @@ +# @babel/generator + +> Turns an AST into code. + +See our website [@babel/generator](https://babeljs.io/docs/en/babel-generator) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A%20generator%22+is%3Aopen) associated with this package. + +## Install + +Using npm: + +```sh +npm install --save-dev @babel/generator +``` + +or using yarn: + +```sh +yarn add @babel/generator --dev +``` diff --git a/node_modules/@babel/generator/lib/buffer.js b/node_modules/@babel/generator/lib/buffer.js new file mode 100644 index 0000000..a2cc377 --- /dev/null +++ b/node_modules/@babel/generator/lib/buffer.js @@ -0,0 +1,354 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +class Buffer { + constructor(map) { + this._map = null; + this._buf = ""; + this._str = ""; + this._appendCount = 0; + this._last = 0; + this._queue = []; + this._queueCursor = 0; + this._position = { + line: 1, + column: 0 + }; + this._sourcePosition = { + identifierName: undefined, + line: undefined, + column: undefined, + filename: undefined + }; + this._map = map; + + this._allocQueue(); + } + + _allocQueue() { + const queue = this._queue; + + for (let i = 0; i < 16; i++) { + queue.push({ + char: 0, + repeat: 1, + line: undefined, + column: undefined, + identifierName: undefined, + filename: "" + }); + } + } + + _pushQueue(char, repeat, line, column, identifierName, filename) { + const cursor = this._queueCursor; + + if (cursor === this._queue.length) { + this._allocQueue(); + } + + const item = this._queue[cursor]; + item.char = char; + item.repeat = repeat; + item.line = line; + item.column = column; + item.identifierName = identifierName; + item.filename = filename; + this._queueCursor++; + } + + _popQueue() { + if (this._queueCursor === 0) { + throw new Error("Cannot pop from empty queue"); + } + + return this._queue[--this._queueCursor]; + } + + get() { + this._flush(); + + const map = this._map; + const result = { + code: (this._buf + this._str).trimRight(), + decodedMap: map == null ? void 0 : map.getDecoded(), + + get map() { + const resultMap = map ? map.get() : null; + result.map = resultMap; + return resultMap; + }, + + set map(value) { + Object.defineProperty(result, "map", { + value, + writable: true + }); + }, + + get rawMappings() { + const mappings = map == null ? void 0 : map.getRawMappings(); + result.rawMappings = mappings; + return mappings; + }, + + set rawMappings(value) { + Object.defineProperty(result, "rawMappings", { + value, + writable: true + }); + } + + }; + return result; + } + + append(str, maybeNewline) { + this._flush(); + + this._append(str, this._sourcePosition, maybeNewline); + } + + appendChar(char) { + this._flush(); + + this._appendChar(char, 1, this._sourcePosition); + } + + queue(char) { + if (char === 10) { + while (this._queueCursor !== 0) { + const char = this._queue[this._queueCursor - 1].char; + + if (char !== 32 && char !== 9) { + break; + } + + this._queueCursor--; + } + } + + const sourcePosition = this._sourcePosition; + + this._pushQueue(char, 1, sourcePosition.line, sourcePosition.column, sourcePosition.identifierName, sourcePosition.filename); + } + + queueIndentation(char, repeat) { + this._pushQueue(char, repeat, undefined, undefined, undefined, undefined); + } + + _flush() { + const queueCursor = this._queueCursor; + const queue = this._queue; + + for (let i = 0; i < queueCursor; i++) { + const item = queue[i]; + + this._appendChar(item.char, item.repeat, item); + } + + this._queueCursor = 0; + } + + _appendChar(char, repeat, sourcePos) { + this._last = char; + this._str += repeat > 1 ? String.fromCharCode(char).repeat(repeat) : String.fromCharCode(char); + + if (char !== 10) { + this._mark(sourcePos.line, sourcePos.column, sourcePos.identifierName, sourcePos.filename); + + this._position.column += repeat; + } else { + this._position.line++; + this._position.column = 0; + } + } + + _append(str, sourcePos, maybeNewline) { + const len = str.length; + const position = this._position; + this._last = str.charCodeAt(len - 1); + + if (++this._appendCount > 4096) { + +this._str; + this._buf += this._str; + this._str = str; + this._appendCount = 0; + } else { + this._str += str; + } + + if (!maybeNewline && !this._map) { + position.column += len; + return; + } + + const { + column, + identifierName, + filename + } = sourcePos; + let line = sourcePos.line; + let i = str.indexOf("\n"); + let last = 0; + + if (i !== 0) { + this._mark(line, column, identifierName, filename); + } + + while (i !== -1) { + position.line++; + position.column = 0; + last = i + 1; + + if (last < len) { + this._mark(++line, 0, identifierName, filename); + } + + i = str.indexOf("\n", last); + } + + position.column += len - last; + } + + _mark(line, column, identifierName, filename) { + var _this$_map; + + (_this$_map = this._map) == null ? void 0 : _this$_map.mark(this._position, line, column, identifierName, filename); + } + + removeTrailingNewline() { + const queueCursor = this._queueCursor; + + if (queueCursor !== 0 && this._queue[queueCursor - 1].char === 10) { + this._queueCursor--; + } + } + + removeLastSemicolon() { + const queueCursor = this._queueCursor; + + if (queueCursor !== 0 && this._queue[queueCursor - 1].char === 59) { + this._queueCursor--; + } + } + + getLastChar() { + const queueCursor = this._queueCursor; + return queueCursor !== 0 ? this._queue[queueCursor - 1].char : this._last; + } + + getNewlineCount() { + const queueCursor = this._queueCursor; + let count = 0; + if (queueCursor === 0) return this._last === 10 ? 1 : 0; + + for (let i = queueCursor - 1; i >= 0; i--) { + if (this._queue[i].char !== 10) { + break; + } + + count++; + } + + return count === queueCursor && this._last === 10 ? count + 1 : count; + } + + endsWithCharAndNewline() { + const queue = this._queue; + const queueCursor = this._queueCursor; + + if (queueCursor !== 0) { + const lastCp = queue[queueCursor - 1].char; + if (lastCp !== 10) return; + + if (queueCursor > 1) { + return queue[queueCursor - 2].char; + } else { + return this._last; + } + } + } + + hasContent() { + return this._queueCursor !== 0 || !!this._last; + } + + exactSource(loc, cb) { + if (!this._map) return cb(); + this.source("start", loc); + cb(); + this.source("end", loc); + } + + source(prop, loc) { + if (!this._map) return; + + this._normalizePosition(prop, loc, 0, 0); + } + + sourceWithOffset(prop, loc, lineOffset, columnOffset) { + if (!this._map) return; + + this._normalizePosition(prop, loc, lineOffset, columnOffset); + } + + withSource(prop, loc, cb) { + if (!this._map) return cb(); + this.source(prop, loc); + cb(); + } + + _normalizePosition(prop, loc, lineOffset, columnOffset) { + const pos = loc[prop]; + const target = this._sourcePosition; + target.identifierName = prop === "start" && loc.identifierName || undefined; + + if (pos) { + target.line = pos.line + lineOffset; + target.column = pos.column + columnOffset; + target.filename = loc.filename; + } + } + + getCurrentColumn() { + const queue = this._queue; + const queueCursor = this._queueCursor; + let lastIndex = -1; + let len = 0; + + for (let i = 0; i < queueCursor; i++) { + const item = queue[i]; + + if (item.char === 10) { + lastIndex = len; + } + + len += item.repeat; + } + + return lastIndex === -1 ? this._position.column + len : len - 1 - lastIndex; + } + + getCurrentLine() { + let count = 0; + const queue = this._queue; + + for (let i = 0; i < this._queueCursor; i++) { + if (queue[i].char === 10) { + count++; + } + } + + return this._position.line + count; + } + +} + +exports.default = Buffer; + +//# sourceMappingURL=buffer.js.map diff --git a/node_modules/@babel/generator/lib/buffer.js.map b/node_modules/@babel/generator/lib/buffer.js.map new file mode 100644 index 0000000..7e70393 --- /dev/null +++ b/node_modules/@babel/generator/lib/buffer.js.map @@ -0,0 +1 @@ +{"version":3,"names":["Buffer","constructor","map","_map","_buf","_str","_appendCount","_last","_queue","_queueCursor","_position","line","column","_sourcePosition","identifierName","undefined","filename","_allocQueue","queue","i","push","char","repeat","_pushQueue","cursor","length","item","_popQueue","Error","get","_flush","result","code","trimRight","decodedMap","getDecoded","resultMap","value","Object","defineProperty","writable","rawMappings","mappings","getRawMappings","append","str","maybeNewline","_append","appendChar","_appendChar","sourcePosition","queueIndentation","queueCursor","sourcePos","String","fromCharCode","_mark","len","position","charCodeAt","indexOf","last","mark","removeTrailingNewline","removeLastSemicolon","getLastChar","getNewlineCount","count","endsWithCharAndNewline","lastCp","hasContent","exactSource","loc","cb","source","prop","_normalizePosition","sourceWithOffset","lineOffset","columnOffset","withSource","pos","target","getCurrentColumn","lastIndex","getCurrentLine"],"sources":["../src/buffer.ts"],"sourcesContent":["import type SourceMap from \"./source-map\";\nimport * as charcodes from \"charcodes\";\n\nexport type Pos = {\n line: number;\n column: number;\n};\nexport type Loc = {\n start?: Pos;\n end?: Pos;\n identifierName?: string;\n filename?: string;\n};\ntype SourcePos = {\n identifierName: string | undefined;\n line: number | undefined;\n column: number | undefined;\n filename: string | undefined;\n};\n\ntype QueueItem = {\n char: number;\n repeat: number;\n line: number | undefined;\n column: number | undefined;\n identifierName: string | undefined;\n filename: string | undefined;\n};\n\nexport default class Buffer {\n constructor(map?: SourceMap | null) {\n this._map = map;\n\n this._allocQueue();\n }\n\n _map: SourceMap = null;\n _buf = \"\";\n _str = \"\";\n _appendCount = 0;\n _last = 0;\n _queue: QueueItem[] = [];\n _queueCursor = 0;\n\n _position = {\n line: 1,\n column: 0,\n };\n _sourcePosition: SourcePos = {\n identifierName: undefined,\n line: undefined,\n column: undefined,\n filename: undefined,\n };\n\n _allocQueue() {\n const queue = this._queue;\n\n for (let i = 0; i < 16; i++) {\n queue.push({\n char: 0,\n repeat: 1,\n line: undefined,\n column: undefined,\n identifierName: undefined,\n filename: \"\",\n });\n }\n }\n\n _pushQueue(\n char: number,\n repeat: number,\n line: number | undefined,\n column: number | undefined,\n identifierName: string | undefined,\n filename: string | undefined,\n ) {\n const cursor = this._queueCursor;\n if (cursor === this._queue.length) {\n this._allocQueue();\n }\n const item = this._queue[cursor];\n item.char = char;\n item.repeat = repeat;\n item.line = line;\n item.column = column;\n item.identifierName = identifierName;\n item.filename = filename;\n\n this._queueCursor++;\n }\n\n _popQueue(): QueueItem {\n if (this._queueCursor === 0) {\n throw new Error(\"Cannot pop from empty queue\");\n }\n return this._queue[--this._queueCursor];\n }\n\n /**\n * Get the final string output from the buffer, along with the sourcemap if one exists.\n */\n\n get() {\n this._flush();\n\n const map = this._map;\n const result = {\n // Whatever trim is used here should not execute a regex against the\n // source string since it may be arbitrarily large after all transformations\n code: (this._buf + this._str).trimRight(),\n // Decoded sourcemap is free to generate.\n decodedMap: map?.getDecoded(),\n\n // Encoding the sourcemap is moderately CPU expensive.\n get map() {\n const resultMap = map ? map.get() : null;\n result.map = resultMap;\n return resultMap;\n },\n set map(value) {\n Object.defineProperty(result, \"map\", { value, writable: true });\n },\n // Retrieving the raw mappings is very memory intensive.\n get rawMappings() {\n const mappings = map?.getRawMappings();\n result.rawMappings = mappings;\n return mappings;\n },\n set rawMappings(value) {\n Object.defineProperty(result, \"rawMappings\", { value, writable: true });\n },\n };\n\n return result;\n }\n\n /**\n * Add a string to the buffer that cannot be reverted.\n */\n\n append(str: string, maybeNewline: boolean): void {\n this._flush();\n\n this._append(str, this._sourcePosition, maybeNewline);\n }\n\n appendChar(char: number): void {\n this._flush();\n this._appendChar(char, 1, this._sourcePosition);\n }\n\n /**\n * Add a string to the buffer than can be reverted.\n */\n queue(char: number): void {\n // Drop trailing spaces when a newline is inserted.\n if (char === charcodes.lineFeed) {\n while (this._queueCursor !== 0) {\n const char = this._queue[this._queueCursor - 1].char;\n if (char !== charcodes.space && char !== charcodes.tab) {\n break;\n }\n\n this._queueCursor--;\n }\n }\n\n const sourcePosition = this._sourcePosition;\n this._pushQueue(\n char,\n 1,\n sourcePosition.line,\n sourcePosition.column,\n sourcePosition.identifierName,\n sourcePosition.filename,\n );\n }\n\n /**\n * Same as queue, but this indentation will never have a sourcmap marker.\n */\n queueIndentation(char: number, repeat: number): void {\n this._pushQueue(char, repeat, undefined, undefined, undefined, undefined);\n }\n\n _flush(): void {\n const queueCursor = this._queueCursor;\n const queue = this._queue;\n for (let i = 0; i < queueCursor; i++) {\n const item: QueueItem = queue[i];\n this._appendChar(item.char, item.repeat, item);\n }\n this._queueCursor = 0;\n }\n\n _appendChar(char: number, repeat: number, sourcePos: SourcePos): void {\n this._last = char;\n\n this._str +=\n repeat > 1\n ? String.fromCharCode(char).repeat(repeat)\n : String.fromCharCode(char);\n\n if (char !== charcodes.lineFeed) {\n this._mark(\n sourcePos.line,\n sourcePos.column,\n sourcePos.identifierName,\n sourcePos.filename,\n );\n this._position.column += repeat;\n } else {\n this._position.line++;\n this._position.column = 0;\n }\n }\n\n _append(str: string, sourcePos: SourcePos, maybeNewline: boolean): void {\n const len = str.length;\n const position = this._position;\n\n this._last = str.charCodeAt(len - 1);\n\n if (++this._appendCount > 4096) {\n +this._str; // Unexplainable huge performance boost. Ref: https://github.com/davidmarkclements/flatstr License: MIT\n this._buf += this._str;\n this._str = str;\n this._appendCount = 0;\n } else {\n this._str += str;\n }\n\n if (!maybeNewline && !this._map) {\n position.column += len;\n return;\n }\n\n const { column, identifierName, filename } = sourcePos;\n let line = sourcePos.line;\n\n // Search for newline chars. We search only for `\\n`, since both `\\r` and\n // `\\r\\n` are normalized to `\\n` during parse. We exclude `\\u2028` and\n // `\\u2029` for performance reasons, they're so uncommon that it's probably\n // ok. It's also unclear how other sourcemap utilities handle them...\n let i = str.indexOf(\"\\n\");\n let last = 0;\n\n // If the string starts with a newline char, then adding a mark is redundant.\n // This catches both \"no newlines\" and \"newline after several chars\".\n if (i !== 0) {\n this._mark(line, column, identifierName, filename);\n }\n\n // Now, find each reamining newline char in the string.\n while (i !== -1) {\n position.line++;\n position.column = 0;\n last = i + 1;\n\n // We mark the start of each line, which happens directly after this newline char\n // unless this is the last char.\n if (last < len) {\n this._mark(++line, 0, identifierName, filename);\n }\n i = str.indexOf(\"\\n\", last);\n }\n position.column += len - last;\n }\n\n _mark(\n line: number | undefined,\n column: number | undefined,\n identifierName: string | undefined,\n filename: string | undefined,\n ): void {\n this._map?.mark(this._position, line, column, identifierName, filename);\n }\n\n removeTrailingNewline(): void {\n const queueCursor = this._queueCursor;\n if (\n queueCursor !== 0 &&\n this._queue[queueCursor - 1].char === charcodes.lineFeed\n ) {\n this._queueCursor--;\n }\n }\n\n removeLastSemicolon(): void {\n const queueCursor = this._queueCursor;\n if (\n queueCursor !== 0 &&\n this._queue[queueCursor - 1].char === charcodes.semicolon\n ) {\n this._queueCursor--;\n }\n }\n\n getLastChar(): number {\n const queueCursor = this._queueCursor;\n return queueCursor !== 0 ? this._queue[queueCursor - 1].char : this._last;\n }\n\n /**\n * This will only detect at most 1 newline after a call to `flush()`,\n * but this has not been found so far, and an accurate count can be achieved if needed later.\n */\n getNewlineCount(): number {\n const queueCursor = this._queueCursor;\n let count = 0;\n if (queueCursor === 0) return this._last === charcodes.lineFeed ? 1 : 0;\n for (let i = queueCursor - 1; i >= 0; i--) {\n if (this._queue[i].char !== charcodes.lineFeed) {\n break;\n }\n count++;\n }\n return count === queueCursor && this._last === charcodes.lineFeed\n ? count + 1\n : count;\n }\n\n /**\n * check if current _last + queue ends with newline, return the character before newline\n *\n * @param {*} ch\n * @memberof Buffer\n */\n endsWithCharAndNewline(): number {\n const queue = this._queue;\n const queueCursor = this._queueCursor;\n if (queueCursor !== 0) {\n // every element in queue is one-length whitespace string\n const lastCp = queue[queueCursor - 1].char;\n if (lastCp !== charcodes.lineFeed) return;\n if (queueCursor > 1) {\n return queue[queueCursor - 2].char;\n } else {\n return this._last;\n }\n }\n // We assume that everything being matched is at most a single token plus some whitespace,\n // which everything currently is, but otherwise we'd have to expand _last or check _buf.\n }\n\n hasContent(): boolean {\n return this._queueCursor !== 0 || !!this._last;\n }\n\n /**\n * Certain sourcemap usecases expect mappings to be more accurate than\n * Babel's generic sourcemap handling allows. For now, we special-case\n * identifiers to allow for the primary cases to work.\n * The goal of this line is to ensure that the map output from Babel will\n * have an exact range on identifiers in the output code. Without this\n * line, Babel would potentially include some number of trailing tokens\n * that are printed after the identifier, but before another location has\n * been assigned.\n * This allows tooling like Rollup and Webpack to more accurately perform\n * their own transformations. Most importantly, this allows the import/export\n * transformations performed by those tools to loose less information when\n * applying their own transformations on top of the code and map results\n * generated by Babel itself.\n *\n * The primary example of this is the snippet:\n *\n * import mod from \"mod\";\n * mod();\n *\n * With this line, there will be one mapping range over \"mod\" and another\n * over \"();\", where previously it would have been a single mapping.\n */\n exactSource(loc: Loc | undefined, cb: () => void) {\n if (!this._map) return cb();\n\n this.source(\"start\", loc);\n\n cb();\n\n this.source(\"end\", loc);\n }\n\n /**\n * Sets a given position as the current source location so generated code after this call\n * will be given this position in the sourcemap.\n */\n\n source(prop: \"start\" | \"end\", loc: Loc | undefined): void {\n if (!this._map) return;\n\n // Since this is called extremely often, we re-use the same _sourcePosition\n // object for the whole lifetime of the buffer.\n this._normalizePosition(prop, loc, 0, 0);\n }\n\n sourceWithOffset(\n prop: \"start\" | \"end\",\n loc: Loc | undefined,\n lineOffset: number,\n columnOffset: number,\n ): void {\n if (!this._map) return;\n\n this._normalizePosition(prop, loc, lineOffset, columnOffset);\n }\n\n /**\n * Call a callback with a specific source location\n */\n\n withSource(prop: \"start\" | \"end\", loc: Loc, cb: () => void): void {\n if (!this._map) return cb();\n\n this.source(prop, loc);\n\n cb();\n }\n\n _normalizePosition(\n prop: \"start\" | \"end\",\n loc: Loc,\n lineOffset: number,\n columnOffset: number,\n ) {\n const pos = loc[prop];\n const target = this._sourcePosition;\n\n target.identifierName =\n (prop === \"start\" && loc.identifierName) || undefined;\n if (pos) {\n target.line = pos.line + lineOffset;\n target.column = pos.column + columnOffset;\n target.filename = loc.filename;\n }\n }\n\n getCurrentColumn(): number {\n const queue = this._queue;\n const queueCursor = this._queueCursor;\n\n let lastIndex = -1;\n let len = 0;\n for (let i = 0; i < queueCursor; i++) {\n const item = queue[i];\n if (item.char === charcodes.lineFeed) {\n lastIndex = len;\n }\n len += item.repeat;\n }\n\n return lastIndex === -1 ? this._position.column + len : len - 1 - lastIndex;\n }\n\n getCurrentLine(): number {\n let count = 0;\n\n const queue = this._queue;\n for (let i = 0; i < this._queueCursor; i++) {\n if (queue[i].char === charcodes.lineFeed) {\n count++;\n }\n }\n\n return this._position.line + count;\n }\n}\n"],"mappings":";;;;;;;AA6Be,MAAMA,MAAN,CAAa;EAC1BC,WAAW,CAACC,GAAD,EAAyB;IAAA,KAMpCC,IANoC,GAMlB,IANkB;IAAA,KAOpCC,IAPoC,GAO7B,EAP6B;IAAA,KAQpCC,IARoC,GAQ7B,EAR6B;IAAA,KASpCC,YAToC,GASrB,CATqB;IAAA,KAUpCC,KAVoC,GAU5B,CAV4B;IAAA,KAWpCC,MAXoC,GAWd,EAXc;IAAA,KAYpCC,YAZoC,GAYrB,CAZqB;IAAA,KAcpCC,SAdoC,GAcxB;MACVC,IAAI,EAAE,CADI;MAEVC,MAAM,EAAE;IAFE,CAdwB;IAAA,KAkBpCC,eAlBoC,GAkBP;MAC3BC,cAAc,EAAEC,SADW;MAE3BJ,IAAI,EAAEI,SAFqB;MAG3BH,MAAM,EAAEG,SAHmB;MAI3BC,QAAQ,EAAED;IAJiB,CAlBO;IAClC,KAAKZ,IAAL,GAAYD,GAAZ;;IAEA,KAAKe,WAAL;EACD;;EAqBDA,WAAW,GAAG;IACZ,MAAMC,KAAK,GAAG,KAAKV,MAAnB;;IAEA,KAAK,IAAIW,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAG,EAApB,EAAwBA,CAAC,EAAzB,EAA6B;MAC3BD,KAAK,CAACE,IAAN,CAAW;QACTC,IAAI,EAAE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J,EAAsC;QACpC+D,SAAS,GAAG3B,GAAZ;MACD;;MACDA,GAAG,IAAI/B,IAAI,CAACJ,MAAZ;IACD;;IAED,OAAO8D,SAAS,KAAK,CAAC,CAAf,GAAmB,KAAK1E,SAAL,CAAeE,MAAf,GAAwB6C,GAA3C,GAAiDA,GAAG,GAAG,CAAN,GAAU2B,SAAlE;EACD;;EAEDC,cAAc,GAAW;IACvB,IAAIlB,KAAK,GAAG,CAAZ;IAEA,MAAMjD,KAAK,GAAG,KAAKV,MAAnB;;IACA,KAAK,IAAIW,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAG,KAAKV,YAAzB,EAAuCU,CAAC,EAAxC,EAA4C;MAC1C,IAAID,KAAK,CAACC,CAAD,CAAL,CAASE,IAAT,OAAJ,EAA0C;QACxC8C,KAAK;MACN;IACF;;IAED,OAAO,KAAKzD,SAAL,CAAeC,IAAf,GAAsBwD,KAA7B;EACD;;AArbyB"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/base.js b/node_modules/@babel/generator/lib/generators/base.js new file mode 100644 index 0000000..3a6513b --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/base.js @@ -0,0 +1,116 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BlockStatement = BlockStatement; +exports.Directive = Directive; +exports.DirectiveLiteral = DirectiveLiteral; +exports.File = File; +exports.InterpreterDirective = InterpreterDirective; +exports.Placeholder = Placeholder; +exports.Program = Program; + +function File(node) { + if (node.program) { + this.print(node.program.interpreter, node); + } + + this.print(node.program, node); +} + +function Program(node) { + var _node$directives; + + this.printInnerComments(node, false); + const directivesLen = (_node$directives = node.directives) == null ? void 0 : _node$directives.length; + + if (directivesLen) { + var _node$directives$trai; + + const newline = node.body.length ? 2 : 1; + this.printSequence(node.directives, node, { + trailingCommentsLineOffset: newline + }); + + if (!((_node$directives$trai = node.directives[directivesLen - 1].trailingComments) != null && _node$directives$trai.length)) { + this.newline(newline); + } + } + + this.printSequence(node.body, node); +} + +function BlockStatement(node) { + var _node$directives2; + + this.tokenChar(123); + this.printInnerComments(node); + const directivesLen = (_node$directives2 = node.directives) == null ? void 0 : _node$directives2.length; + + if (directivesLen) { + var _node$directives$trai2; + + const newline = node.body.length ? 2 : 1; + this.printSequence(node.directives, node, { + indent: true, + trailingCommentsLineOffset: newline + }); + + if (!((_node$directives$trai2 = node.directives[directivesLen - 1].trailingComments) != null && _node$directives$trai2.length)) { + this.newline(newline); + } + } + + this.printSequence(node.body, node, { + indent: true + }); + this.sourceWithOffset("end", node.loc, 0, -1); + this.rightBrace(); +} + +function Directive(node) { + this.print(node.value, node); + this.semicolon(); +} + +const unescapedSingleQuoteRE = /(?:^|[^\\])(?:\\\\)*'/; +const unescapedDoubleQuoteRE = /(?:^|[^\\])(?:\\\\)*"/; + +function DirectiveLiteral(node) { + const raw = this.getPossibleRaw(node); + + if (!this.format.minified && raw !== undefined) { + this.token(raw); + return; + } + + const { + value + } = node; + + if (!unescapedDoubleQuoteRE.test(value)) { + this.token(`"${value}"`); + } else if (!unescapedSingleQuoteRE.test(value)) { + this.token(`'${value}'`); + } else { + throw new Error("Malformed AST: it is not possible to print a directive containing" + " both unescaped single and double quotes."); + } +} + +function InterpreterDirective(node) { + this.token(`#!${node.value}`); + this.newline(1, true); +} + +function Placeholder(node) { + this.token("%%"); + this.print(node.name); + this.token("%%"); + + if (node.expectedNode === "Statement") { + this.semicolon(); + } +} + +//# sourceMappingURL=base.js.map diff --git a/node_modules/@babel/generator/lib/generators/base.js.map b/node_modules/@babel/generator/lib/generators/base.js.map new file mode 100644 index 0000000..65a7d35 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/base.js.map @@ -0,0 +1 @@ +{"version":3,"names":["File","node","program","print","interpreter","Program","printInnerComments","directivesLen","directives","length","newline","body","printSequence","trailingCommentsLineOffset","trailingComments","BlockStatement","token","indent","sourceWithOffset","loc","rightBrace","Directive","value","semicolon","unescapedSingleQuoteRE","unescapedDoubleQuoteRE","DirectiveLiteral","raw","getPossibleRaw","format","minified","undefined","test","Error","InterpreterDirective","Placeholder","name","expectedNode"],"sources":["../../src/generators/base.ts"],"sourcesContent":["import type Printer from \"../printer\";\nimport type * as t from \"@babel/types\";\n\nexport function File(this: Printer, node: t.File) {\n if (node.program) {\n // Print this here to ensure that Program node 'leadingComments' still\n // get printed after the hashbang.\n this.print(node.program.interpreter, node);\n }\n\n this.print(node.program, node);\n}\n\nexport function Program(this: Printer, node: t.Program) {\n this.printInnerComments(node, false);\n\n const directivesLen = node.directives?.length;\n if (directivesLen) {\n const newline = node.body.length ? 2 : 1;\n this.printSequence(node.directives, node, {\n trailingCommentsLineOffset: newline,\n });\n if (!node.directives[directivesLen - 1].trailingComments?.length) {\n this.newline(newline);\n }\n }\n\n this.printSequence(node.body, node);\n}\n\nexport function BlockStatement(this: Printer, node: t.BlockStatement) {\n this.token(\"{\");\n this.printInnerComments(node);\n\n const directivesLen = node.directives?.length;\n if (directivesLen) {\n const newline = node.body.length ? 2 : 1;\n this.printSequence(node.directives, node, {\n indent: true,\n trailingCommentsLineOffset: newline,\n });\n if (!node.directives[directivesLen - 1].trailingComments?.length) {\n this.newline(newline);\n }\n }\n\n this.printSequence(node.body, node, { indent: true });\n\n this.sourceWithOffset(\"end\", node.loc, 0, -1);\n\n this.rightBrace();\n}\n\nexport function Directive(this: Printer, node: t.Directive) {\n this.print(node.value, node);\n this.semicolon();\n}\n\n// These regexes match an even number of \\ followed by a quote\nconst unescapedSingleQuoteRE = /(?:^|[^\\\\])(?:\\\\\\\\)*'/;\nconst unescapedDoubleQuoteRE = /(?:^|[^\\\\])(?:\\\\\\\\)*\"/;\n\nexport function DirectiveLiteral(this: Printer, node: t.DirectiveLiteral) {\n const raw = this.getPossibleRaw(node);\n if (!this.format.minified && raw !== undefined) {\n this.token(raw);\n return;\n }\n\n const { value } = node;\n\n // NOTE: In directives we can't change escapings,\n // because they change the behavior.\n // e.g. \"us\\x65 string\" (\\x65 is e) is not a \"use strict\" directive.\n\n if (!unescapedDoubleQuoteRE.test(value)) {\n this.token(`\"${value}\"`);\n } else if (!unescapedSingleQuoteRE.test(value)) {\n this.token(`'${value}'`);\n } else {\n throw new Error(\n \"Malformed AST: it is not possible to print a directive containing\" +\n \" both unescaped single and double quotes.\",\n );\n }\n}\n\nexport function InterpreterDirective(\n this: Printer,\n node: t.InterpreterDirective,\n) {\n this.token(`#!${node.value}`);\n this.newline(1, true);\n}\n\nexport function Placeholder(this: Printer, node: t.Placeholder) {\n this.token(\"%%\");\n this.print(node.name);\n this.token(\"%%\");\n\n if (node.expectedNode === \"Statement\") {\n this.semicolon();\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAGO,SAASA,IAAT,CAA6BC,IAA7B,EAA2C;EAChD,IAAIA,IAAI,CAACC,OAAT,EAAkB;IAGhB,KAAKC,KAAL,CAAWF,IAAI,CAACC,OAAL,CAAaE,WAAxB,EAAqCH,IAArC;EACD;;EAED,KAAKE,KAAL,CAAWF,IAAI,CAACC,OAAhB,EAAyBD,IAAzB;AACD;;AAEM,SAASI,OAAT,CAAgCJ,IAAhC,EAAiD;EAAA;;EACtD,KAAKK,kBAAL,CAAwBL,IAAxB,EAA8B,KAA9B;EAEA,MAAMM,aAAa,uBAAGN,IAAI,CAACO,UAAR,qBAAG,iBAAiBC,MAAvC;;EACA,IAAIF,aAAJ,EAAmB;IAAA;;IACjB,MAAMG,OAAO,GAAGT,IAAI,CAACU,IAAL,CAAUF,MAAV,GAAmB,CAAnB,GAAuB,CAAvC;IACA,KAAKG,aAAL,CAAmBX,IAAI,CAACO,UAAxB,EAAoCP,IAApC,EAA0C;MACxCY,0BAA0B,EAAEH;IADY,CAA1C;;IAGA,IAAI,2BAACT,IAAI,CAACO,UAAL,CAAgBD,aAAa,GAAG,CAAhC,EAAmCO,gBAApC,aAAC,sBAAqDL,MAAtD,CAAJ,EAAkE;MAChE,KAAKC,OAAL,CAAaA,OAAb;IACD;EACF;;EAED,KAAKE,aAAL,CAAmBX,IAAI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,EAAgD;IAC9C,KAAKf,KAAL,CAAWW,GAAX;IACA;EACD;;EAED,MAAM;IAAEL;EAAF,IAAYrB,IAAlB;;EAMA,IAAI,CAACwB,sBAAsB,CAACO,IAAvB,CAA4BV,KAA5B,CAAL,EAAyC;IACvC,KAAKN,KAAL,CAAY,IAAGM,KAAM,GAArB;EACD,CAFD,MAEO,IAAI,CAACE,sBAAsB,CAACQ,IAAvB,CAA4BV,KAA5B,CAAL,EAAyC;IAC9C,KAAKN,KAAL,CAAY,IAAGM,KAAM,GAArB;EACD,CAFM,MAEA;IACL,MAAM,IAAIW,KAAJ,CACJ,sEACE,2CAFE,CAAN;EAID;AACF;;AAEM,SAASC,oBAAT,CAELjC,IAFK,EAGL;EACA,KAAKe,KAAL,CAAY,KAAIf,IAAI,CAACqB,KAAM,EAA3B;EACA,KAAKZ,OAAL,CAAa,CAAb,EAAgB,IAAhB;AACD;;AAEM,SAASyB,WAAT,CAAoClC,IAApC,EAAyD;EAC9D,KAAKe,KAAL,CAAW,IAAX;EACA,KAAKb,KAAL,CAAWF,IAAI,CAACmC,IAAhB;EACA,KAAKpB,KAAL,CAAW,IAAX;;EAEA,IAAIf,IAAI,CAACoC,YAAL,KAAsB,WAA1B,EAAuC;IACrC,KAAKd,SAAL;EACD;AACF"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/classes.js b/node_modules/@babel/generator/lib/generators/classes.js new file mode 100644 index 0000000..39ee20c --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/classes.js @@ -0,0 +1,228 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ClassAccessorProperty = ClassAccessorProperty; +exports.ClassBody = ClassBody; +exports.ClassExpression = exports.ClassDeclaration = ClassDeclaration; +exports.ClassMethod = ClassMethod; +exports.ClassPrivateMethod = ClassPrivateMethod; +exports.ClassPrivateProperty = ClassPrivateProperty; +exports.ClassProperty = ClassProperty; +exports.StaticBlock = StaticBlock; +exports._classMethodHead = _classMethodHead; + +var _t = require("@babel/types"); + +const { + isExportDefaultDeclaration, + isExportNamedDeclaration +} = _t; + +function ClassDeclaration(node, parent) { + { + if (!this.format.decoratorsBeforeExport || !isExportDefaultDeclaration(parent) && !isExportNamedDeclaration(parent)) { + this.printJoin(node.decorators, node); + } + } + + if (node.declare) { + this.word("declare"); + this.space(); + } + + if (node.abstract) { + this.word("abstract"); + this.space(); + } + + this.word("class"); + this.printInnerComments(node); + + if (node.id) { + this.space(); + this.print(node.id, node); + } + + this.print(node.typeParameters, node); + + if (node.superClass) { + this.space(); + this.word("extends"); + this.space(); + this.print(node.superClass, node); + this.print(node.superTypeParameters, node); + } + + if (node.implements) { + this.space(); + this.word("implements"); + this.space(); + this.printList(node.implements, node); + } + + this.space(); + this.print(node.body, node); +} + +function ClassBody(node) { + this.tokenChar(123); + this.printInnerComments(node); + + if (node.body.length === 0) { + this.tokenChar(125); + } else { + this.newline(); + this.indent(); + this.printSequence(node.body, node); + this.dedent(); + if (!this.endsWith(10)) this.newline(); + this.sourceWithOffset("end", node.loc, 0, -1); + this.rightBrace(); + } +} + +function ClassProperty(node) { + var _node$key$loc, _node$key$loc$end; + + this.printJoin(node.decorators, node); + const endLine = (_node$key$loc = node.key.loc) == null ? void 0 : (_node$key$loc$end = _node$key$loc.end) == null ? void 0 : _node$key$loc$end.line; + if (endLine) this.catchUp(endLine); + this.tsPrintClassMemberModifiers(node); + + if (node.computed) { + this.tokenChar(91); + this.print(node.key, node); + this.tokenChar(93); + } else { + this._variance(node); + + this.print(node.key, node); + } + + if (node.optional) { + this.tokenChar(63); + } + + if (node.definite) { + this.tokenChar(33); + } + + this.print(node.typeAnnotation, node); + + if (node.value) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.value, node); + } + + this.semicolon(); +} + +function ClassAccessorProperty(node) { + var _node$key$loc2, _node$key$loc2$end; + + this.printJoin(node.decorators, node); + const endLine = (_node$key$loc2 = node.key.loc) == null ? void 0 : (_node$key$loc2$end = _node$key$loc2.end) == null ? void 0 : _node$key$loc2$end.line; + if (endLine) this.catchUp(endLine); + this.tsPrintClassMemberModifiers(node); + this.word("accessor"); + this.printInnerComments(node); + this.space(); + + if (node.computed) { + this.tokenChar(91); + this.print(node.key, node); + this.tokenChar(93); + } else { + this._variance(node); + + this.print(node.key, node); + } + + if (node.optional) { + this.tokenChar(63); + } + + if (node.definite) { + this.tokenChar(33); + } + + this.print(node.typeAnnotation, node); + + if (node.value) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.value, node); + } + + this.semicolon(); +} + +function ClassPrivateProperty(node) { + this.printJoin(node.decorators, node); + + if (node.static) { + this.word("static"); + this.space(); + } + + this.print(node.key, node); + this.print(node.typeAnnotation, node); + + if (node.value) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.value, node); + } + + this.semicolon(); +} + +function ClassMethod(node) { + this._classMethodHead(node); + + this.space(); + this.print(node.body, node); +} + +function ClassPrivateMethod(node) { + this._classMethodHead(node); + + this.space(); + this.print(node.body, node); +} + +function _classMethodHead(node) { + var _node$key$loc3, _node$key$loc3$end; + + this.printJoin(node.decorators, node); + const endLine = (_node$key$loc3 = node.key.loc) == null ? void 0 : (_node$key$loc3$end = _node$key$loc3.end) == null ? void 0 : _node$key$loc3$end.line; + if (endLine) this.catchUp(endLine); + this.tsPrintClassMemberModifiers(node); + + this._methodHead(node); +} + +function StaticBlock(node) { + this.word("static"); + this.space(); + this.tokenChar(123); + + if (node.body.length === 0) { + this.tokenChar(125); + } else { + this.newline(); + this.printSequence(node.body, node, { + indent: true + }); + this.sourceWithOffset("end", node.loc, 0, -1); + this.rightBrace(); + } +} + +//# sourceMappingURL=classes.js.map diff --git a/node_modules/@babel/generator/lib/generators/classes.js.map b/node_modules/@babel/generator/lib/generators/classes.js.map new file mode 100644 index 0000000..0ba1d6f --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/classes.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isExportDefaultDeclaration","isExportNamedDeclaration","ClassDeclaration","node","parent","format","decoratorsBeforeExport","printJoin","decorators","declare","word","space","abstract","printInnerComments","id","print","typeParameters","superClass","superTypeParameters","implements","printList","body","ClassBody","token","length","newline","indent","printSequence","dedent","endsWith","sourceWithOffset","loc","rightBrace","ClassProperty","endLine","key","end","line","catchUp","tsPrintClassMemberModifiers","computed","_variance","optional","definite","typeAnnotation","value","semicolon","ClassAccessorProperty","ClassPrivateProperty","static","ClassMethod","_classMethodHead","ClassPrivateMethod","_methodHead","StaticBlock"],"sources":["../../src/generators/classes.ts"],"sourcesContent":["import type Printer from \"../printer\";\nimport {\n isExportDefaultDeclaration,\n isExportNamedDeclaration,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport * as charCodes from \"charcodes\";\n\nexport function ClassDeclaration(\n this: Printer,\n node: t.ClassDeclaration,\n parent: t.Node,\n) {\n if (process.env.BABEL_8_BREAKING) {\n this.printJoin(node.decorators, node);\n } else {\n if (\n !this.format.decoratorsBeforeExport ||\n (!isExportDefaultDeclaration(parent) && !isExportNamedDeclaration(parent))\n ) {\n this.printJoin(node.decorators, node);\n }\n }\n\n if (node.declare) {\n // TS\n this.word(\"declare\");\n this.space();\n }\n\n if (node.abstract) {\n // TS\n this.word(\"abstract\");\n this.space();\n }\n\n this.word(\"class\");\n this.printInnerComments(node);\n\n if (node.id) {\n this.space();\n this.print(node.id, node);\n }\n\n this.print(node.typeParameters, node);\n\n if (node.superClass) {\n this.space();\n this.word(\"extends\");\n this.space();\n this.print(node.superClass, node);\n this.print(node.superTypeParameters, node);\n }\n\n if (node.implements) {\n this.space();\n this.word(\"implements\");\n this.space();\n this.printList(node.implements, node);\n }\n\n this.space();\n this.print(node.body, node);\n}\n\nexport { ClassDeclaration as ClassExpression };\n\nexport function ClassBody(this: Printer, node: t.ClassBody) {\n this.token(\"{\");\n this.printInnerComments(node);\n if (node.body.length === 0) {\n this.token(\"}\");\n } else {\n this.newline();\n\n this.indent();\n this.printSequence(node.body, node);\n this.dedent();\n\n if (!this.endsWith(charCodes.lineFeed)) this.newline();\n\n this.sourceWithOffset(\"end\", node.loc, 0, -1);\n\n this.rightBrace();\n }\n}\n\nexport function ClassProperty(this: Printer, node: t.ClassProperty) {\n this.printJoin(node.decorators, node);\n\n // catch up to property key, avoid line break\n // between member modifiers and the property key.\n const endLine = node.key.loc?.end?.line;\n if (endLine) this.catchUp(endLine);\n\n this.tsPrintClassMemberModifiers(node);\n\n if (node.computed) {\n this.token(\"[\");\n this.print(node.key, node);\n this.token(\"]\");\n } else {\n this._variance(node);\n this.print(node.key, node);\n }\n\n // TS\n if (node.optional) {\n this.token(\"?\");\n }\n if (node.definite) {\n this.token(\"!\");\n }\n\n this.print(node.typeAnnotation, node);\n if (node.value) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.value, node);\n }\n this.semicolon();\n}\n\nexport function ClassAccessorProperty(\n this: Printer,\n node: t.ClassAccessorProperty,\n) {\n this.printJoin(node.decorators, node);\n\n // catch up to property key, avoid line break\n // between member modifiers and the property key.\n const endLine = node.key.loc?.end?.line;\n if (endLine) this.catchUp(endLine);\n\n // TS does not support class accessor property yet\n this.tsPrintClassMemberModifiers(node);\n\n this.word(\"accessor\");\n this.printInnerComments(node);\n this.space();\n\n if (node.computed) {\n this.token(\"[\");\n this.print(node.key, node);\n this.token(\"]\");\n } else {\n // Todo: Flow does not support class accessor property yet.\n this._variance(node);\n this.print(node.key, node);\n }\n\n // TS\n if (node.optional) {\n this.token(\"?\");\n }\n if (node.definite) {\n this.token(\"!\");\n }\n\n this.print(node.typeAnnotation, node);\n if (node.value) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.value, node);\n }\n this.semicolon();\n}\n\nexport function ClassPrivateProperty(\n this: Printer,\n node: t.ClassPrivateProperty,\n) {\n this.printJoin(node.decorators, node);\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n this.print(node.key, node);\n this.print(node.typeAnnotation, node);\n if (node.value) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.value, node);\n }\n this.semicolon();\n}\n\nexport function ClassMethod(this: Printer, node: t.ClassMethod) {\n this._classMethodHead(node);\n this.space();\n this.print(node.body, node);\n}\n\nexport function ClassPrivateMethod(this: Printer, node: t.ClassPrivateMethod) {\n this._classMethodHead(node);\n this.space();\n this.print(node.body, node);\n}\n\nexport function _classMethodHead(\n this: Printer,\n node: t.ClassMethod | t.ClassPrivateMethod | t.TSDeclareMethod,\n) {\n this.printJoin(node.decorators, node);\n\n // catch up to method key, avoid line break\n // between member modifiers/method heads and the method key.\n const endLine = node.key.loc?.end?.line;\n if (endLine) this.catchUp(endLine);\n\n this.tsPrintClassMemberModifiers(node);\n this._methodHead(node);\n}\n\nexport function StaticBlock(this: Printer, node: t.StaticBlock) {\n this.word(\"static\");\n this.space();\n this.token(\"{\");\n if (node.body.length === 0) {\n this.token(\"}\");\n } else {\n this.newline();\n this.printSequence(node.body, node, {\n indent: true,\n });\n\n this.sourceWithOffset(\"end\", node.loc, 0, -1);\n\n this.rightBrace();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AACA;;;EACEA,0B;EACAC;;;AAKK,SAASC,gBAAT,CAELC,IAFK,EAGLC,MAHK,EAIL;EAGO;IACL,IACE,CAAC,KAAKC,MAAL,CAAYC,sBAAb,IACC,CAACN,0BAA0B,CAACI,MAAD,CAA3B,IAAuC,CAACH,wBAAwB,CAACG,MAAD,CAFnE,EAGE;MACA,KAAKG,SAAL,CAAeJ,IAAI,CAACK,UAApB,EAAgCL,IAAhC;IACD;EACF;;EAED,IAAIA,IAAI,CAACM,OAAT,EAAkB;IAEhB,KAAKC,IAAL,CAAU,SAAV;IACA,KAAKC,KAAL;EACD;;EAED,IAAIR,IAAI,CAACS,QAAT,EAAmB;IAEjB,KAAKF,IAAL,CAAU,UAAV;IACA,KAAKC,KAAL;EACD;;EAED,KAAKD,IAAL,CAAU,OAAV;EACA,KAAKG,kBAAL,CAAwBV,IAAxB;;EAEA,IAAIA,IAAI,CAACW,EAAT,EAAa;IACX,KAA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AoC/C,IAApC,EAAyD;EAC9D,KAAKgD,gBAAL,CAAsBhD,IAAtB;;EACA,KAAKQ,KAAL;EACA,KAAKI,KAAL,CAAWZ,IAAI,CAACkB,IAAhB,EAAsBlB,IAAtB;AACD;;AAEM,SAASiD,kBAAT,CAA2CjD,IAA3C,EAAuE;EAC5E,KAAKgD,gBAAL,CAAsBhD,IAAtB;;EACA,KAAKQ,KAAL;EACA,KAAKI,KAAL,CAAWZ,IAAI,CAACkB,IAAhB,EAAsBlB,IAAtB;AACD;;AAEM,SAASgD,gBAAT,CAELhD,IAFK,EAGL;EAAA;;EACA,KAAKI,SAAL,CAAeJ,IAAI,CAACK,UAApB,EAAgCL,IAAhC;EAIA,MAAM+B,OAAO,qBAAG/B,IAAI,CAACgC,GAAL,CAASJ,GAAZ,2CAAG,eAAcK,GAAjB,qBAAG,mBAAmBC,IAAnC;EACA,IAAIH,OAAJ,EAAa,KAAKI,OAAL,CAAaJ,OAAb;EAEb,KAAKK,2BAAL,CAAiCpC,IAAjC;;EACA,KAAKkD,WAAL,CAAiBlD,IAAjB;AACD;;AAEM,SAASmD,WAAT,CAAoCnD,IAApC,EAAyD;EAC9D,KAAKO,IAAL,CAAU,QAAV;EACA,KAAKC,KAAL;EACA,KAAKY,SAAL;;EACA,IAAIpB,IAAI,CAACkB,IAAL,CAAUG,MAAV,KAAqB,CAAzB,EAA4B;IAC1B,KAAKD,SAAL;EACD,CAFD,MAEO;IACL,KAAKE,OAAL;IACA,KAAKE,aAAL,CAAmBxB,IAAI,CAACkB,IAAxB,EAA8BlB,IAA9B,EAAoC;MAClCuB,MAAM,EAAE;IAD0B,CAApC;IAIA,KAAKI,gBAAL,CAAsB,KAAtB,EAA6B3B,IAAI,CAAC4B,GAAlC,EAAuC,CAAvC,EAA0C,CAAC,CAA3C;IAEA,KAAKC,UAAL;EACD;AACF"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/expressions.js b/node_modules/@babel/generator/lib/generators/expressions.js new file mode 100644 index 0000000..839d061 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/expressions.js @@ -0,0 +1,356 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LogicalExpression = exports.BinaryExpression = exports.AssignmentExpression = AssignmentExpression; +exports.AssignmentPattern = AssignmentPattern; +exports.AwaitExpression = AwaitExpression; +exports.BindExpression = BindExpression; +exports.CallExpression = CallExpression; +exports.ConditionalExpression = ConditionalExpression; +exports.Decorator = Decorator; +exports.DoExpression = DoExpression; +exports.EmptyStatement = EmptyStatement; +exports.ExpressionStatement = ExpressionStatement; +exports.Import = Import; +exports.MemberExpression = MemberExpression; +exports.MetaProperty = MetaProperty; +exports.ModuleExpression = ModuleExpression; +exports.NewExpression = NewExpression; +exports.OptionalCallExpression = OptionalCallExpression; +exports.OptionalMemberExpression = OptionalMemberExpression; +exports.ParenthesizedExpression = ParenthesizedExpression; +exports.PrivateName = PrivateName; +exports.SequenceExpression = SequenceExpression; +exports.Super = Super; +exports.ThisExpression = ThisExpression; +exports.UnaryExpression = UnaryExpression; +exports.UpdateExpression = UpdateExpression; +exports.V8IntrinsicIdentifier = V8IntrinsicIdentifier; +exports.YieldExpression = YieldExpression; + +var _t = require("@babel/types"); + +var n = require("../node"); + +const { + isCallExpression, + isLiteral, + isMemberExpression, + isNewExpression +} = _t; + +function UnaryExpression(node) { + if (node.operator === "void" || node.operator === "delete" || node.operator === "typeof" || node.operator === "throw") { + this.word(node.operator); + this.space(); + } else { + this.token(node.operator); + } + + this.print(node.argument, node); +} + +function DoExpression(node) { + if (node.async) { + this.word("async"); + this.space(); + } + + this.word("do"); + this.space(); + this.print(node.body, node); +} + +function ParenthesizedExpression(node) { + this.tokenChar(40); + this.print(node.expression, node); + this.tokenChar(41); +} + +function UpdateExpression(node) { + if (node.prefix) { + this.token(node.operator); + this.print(node.argument, node); + } else { + this.printTerminatorless(node.argument, node, true); + this.token(node.operator); + } +} + +function ConditionalExpression(node) { + this.print(node.test, node); + this.space(); + this.tokenChar(63); + this.space(); + this.print(node.consequent, node); + this.space(); + this.tokenChar(58); + this.space(); + this.print(node.alternate, node); +} + +function NewExpression(node, parent) { + this.word("new"); + this.space(); + this.print(node.callee, node); + + if (this.format.minified && node.arguments.length === 0 && !node.optional && !isCallExpression(parent, { + callee: node + }) && !isMemberExpression(parent) && !isNewExpression(parent)) { + return; + } + + this.print(node.typeArguments, node); + this.print(node.typeParameters, node); + + if (node.optional) { + this.token("?."); + } + + this.tokenChar(40); + this.printList(node.arguments, node); + this.tokenChar(41); +} + +function SequenceExpression(node) { + this.printList(node.expressions, node); +} + +function ThisExpression() { + this.word("this"); +} + +function Super() { + this.word("super"); +} + +function isDecoratorMemberExpression(node) { + switch (node.type) { + case "Identifier": + return true; + + case "MemberExpression": + return !node.computed && node.property.type === "Identifier" && isDecoratorMemberExpression(node.object); + + default: + return false; + } +} + +function shouldParenthesizeDecoratorExpression(node) { + if (node.type === "ParenthesizedExpression") { + return false; + } + + return !isDecoratorMemberExpression(node.type === "CallExpression" ? node.callee : node); +} + +function Decorator(node) { + this.tokenChar(64); + const { + expression + } = node; + + if (shouldParenthesizeDecoratorExpression(expression)) { + this.tokenChar(40); + this.print(expression, node); + this.tokenChar(41); + } else { + this.print(expression, node); + } + + this.newline(); +} + +function OptionalMemberExpression(node) { + this.print(node.object, node); + + if (!node.computed && isMemberExpression(node.property)) { + throw new TypeError("Got a MemberExpression for MemberExpression property"); + } + + let computed = node.computed; + + if (isLiteral(node.property) && typeof node.property.value === "number") { + computed = true; + } + + if (node.optional) { + this.token("?."); + } + + if (computed) { + this.tokenChar(91); + this.print(node.property, node); + this.tokenChar(93); + } else { + if (!node.optional) { + this.tokenChar(46); + } + + this.print(node.property, node); + } +} + +function OptionalCallExpression(node) { + this.print(node.callee, node); + this.print(node.typeParameters, node); + + if (node.optional) { + this.token("?."); + } + + this.print(node.typeArguments, node); + this.tokenChar(40); + this.printList(node.arguments, node); + this.tokenChar(41); +} + +function CallExpression(node) { + this.print(node.callee, node); + this.print(node.typeArguments, node); + this.print(node.typeParameters, node); + this.tokenChar(40); + this.printList(node.arguments, node); + this.tokenChar(41); +} + +function Import() { + this.word("import"); +} + +function AwaitExpression(node) { + this.word("await"); + + if (node.argument) { + this.space(); + this.printTerminatorless(node.argument, node, false); + } +} + +function YieldExpression(node) { + this.word("yield"); + + if (node.delegate) { + this.tokenChar(42); + } + + if (node.argument) { + this.space(); + this.printTerminatorless(node.argument, node, false); + } +} + +function EmptyStatement() { + this.semicolon(true); +} + +function ExpressionStatement(node) { + this.print(node.expression, node); + this.semicolon(); +} + +function AssignmentPattern(node) { + this.print(node.left, node); + if (node.left.optional) this.tokenChar(63); + this.print(node.left.typeAnnotation, node); + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.right, node); +} + +function AssignmentExpression(node, parent) { + const parens = this.inForStatementInitCounter && node.operator === "in" && !n.needsParens(node, parent); + + if (parens) { + this.tokenChar(40); + } + + this.print(node.left, node); + this.space(); + + if (node.operator === "in" || node.operator === "instanceof") { + this.word(node.operator); + } else { + this.token(node.operator); + } + + this.space(); + this.print(node.right, node); + + if (parens) { + this.tokenChar(41); + } +} + +function BindExpression(node) { + this.print(node.object, node); + this.token("::"); + this.print(node.callee, node); +} + +function MemberExpression(node) { + this.print(node.object, node); + + if (!node.computed && isMemberExpression(node.property)) { + throw new TypeError("Got a MemberExpression for MemberExpression property"); + } + + let computed = node.computed; + + if (isLiteral(node.property) && typeof node.property.value === "number") { + computed = true; + } + + if (computed) { + this.tokenChar(91); + this.print(node.property, node); + this.tokenChar(93); + } else { + this.tokenChar(46); + this.print(node.property, node); + } +} + +function MetaProperty(node) { + this.print(node.meta, node); + this.tokenChar(46); + this.print(node.property, node); +} + +function PrivateName(node) { + this.tokenChar(35); + this.print(node.id, node); +} + +function V8IntrinsicIdentifier(node) { + this.tokenChar(37); + this.word(node.name); +} + +function ModuleExpression(node) { + this.word("module"); + this.ensureNoLineTerminator(() => { + this.printInnerComments(node); + this.space(); + }); + this.tokenChar(123); + this.indent(); + const { + body + } = node; + + if (body.body.length || body.directives.length) { + this.newline(); + } + + this.print(body, node); + this.dedent(); + this.sourceWithOffset("end", node.loc, 0, -1); + this.rightBrace(); +} + +//# sourceMappingURL=expressions.js.map diff --git a/node_modules/@babel/generator/lib/generators/expressions.js.map b/node_modules/@babel/generator/lib/generators/expressions.js.map new file mode 100644 index 0000000..25b4f21 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/expressions.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isCallExpression","isLiteral","isMemberExpression","isNewExpression","UnaryExpression","node","operator","word","space","token","print","argument","DoExpression","async","body","ParenthesizedExpression","expression","UpdateExpression","prefix","printTerminatorless","ConditionalExpression","test","consequent","alternate","NewExpression","parent","callee","format","minified","arguments","length","optional","typeArguments","typeParameters","printList","SequenceExpression","expressions","ThisExpression","Super","isDecoratorMemberExpression","type","computed","property","object","shouldParenthesizeDecoratorExpression","Decorator","newline","OptionalMemberExpression","TypeError","value","OptionalCallExpression","CallExpression","Import","AwaitExpression","YieldExpression","delegate","EmptyStatement","semicolon","ExpressionStatement","AssignmentPattern","left","typeAnnotation","right","AssignmentExpression","parens","inForStatementInitCounter","n","needsParens","BindExpression","MemberExpression","MetaProperty","meta","PrivateName","id","V8IntrinsicIdentifier","name","ModuleExpression","ensureNoLineTerminator","printInnerComments","indent","directives","dedent","sourceWithOffset","loc","rightBrace"],"sources":["../../src/generators/expressions.ts"],"sourcesContent":["import type Printer from \"../printer\";\nimport {\n isCallExpression,\n isLiteral,\n isMemberExpression,\n isNewExpression,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport * as n from \"../node\";\n\nexport function UnaryExpression(this: Printer, node: t.UnaryExpression) {\n if (\n node.operator === \"void\" ||\n node.operator === \"delete\" ||\n node.operator === \"typeof\" ||\n // throwExpressions\n node.operator === \"throw\"\n ) {\n this.word(node.operator);\n this.space();\n } else {\n this.token(node.operator);\n }\n\n this.print(node.argument, node);\n}\n\nexport function DoExpression(this: Printer, node: t.DoExpression) {\n if (node.async) {\n this.word(\"async\");\n this.space();\n }\n this.word(\"do\");\n this.space();\n this.print(node.body, node);\n}\n\nexport function ParenthesizedExpression(\n this: Printer,\n node: t.ParenthesizedExpression,\n) {\n this.token(\"(\");\n this.print(node.expression, node);\n this.token(\")\");\n}\n\nexport function UpdateExpression(this: Printer, node: t.UpdateExpression) {\n if (node.prefix) {\n this.token(node.operator);\n this.print(node.argument, node);\n } else {\n this.printTerminatorless(node.argument, node, true);\n this.token(node.operator);\n }\n}\n\nexport function ConditionalExpression(\n this: Printer,\n node: t.ConditionalExpression,\n) {\n this.print(node.test, node);\n this.space();\n this.token(\"?\");\n this.space();\n this.print(node.consequent, node);\n this.space();\n this.token(\":\");\n this.space();\n this.print(node.alternate, node);\n}\n\nexport function NewExpression(\n this: Printer,\n node: t.NewExpression,\n parent: t.Node,\n) {\n this.word(\"new\");\n this.space();\n this.print(node.callee, node);\n if (\n this.format.minified &&\n node.arguments.length === 0 &&\n !node.optional &&\n !isCallExpression(parent, { callee: node }) &&\n !isMemberExpression(parent) &&\n !isNewExpression(parent)\n ) {\n return;\n }\n\n this.print(node.typeArguments, node); // Flow\n this.print(node.typeParameters, node); // TS\n\n if (node.optional) {\n // TODO: This can never happen\n this.token(\"?.\");\n }\n this.token(\"(\");\n this.printList(node.arguments, node);\n this.token(\")\");\n}\n\nexport function SequenceExpression(this: Printer, node: t.SequenceExpression) {\n this.printList(node.expressions, node);\n}\n\nexport function ThisExpression(this: Printer) {\n this.word(\"this\");\n}\n\nexport function Super(this: Printer) {\n this.word(\"super\");\n}\n\nfunction isDecoratorMemberExpression(\n node: t.Expression | t.Super | t.V8IntrinsicIdentifier,\n): boolean {\n switch (node.type) {\n case \"Identifier\":\n return true;\n case \"MemberExpression\":\n return (\n !node.computed &&\n node.property.type === \"Identifier\" &&\n isDecoratorMemberExpression(node.object)\n );\n default:\n return false;\n }\n}\nfunction shouldParenthesizeDecoratorExpression(\n node: t.Expression | t.Super | t.V8IntrinsicIdentifier,\n) {\n if (node.type === \"ParenthesizedExpression\") {\n // We didn't check extra?.parenthesized here because we don't track decorators in needsParen\n return false;\n }\n return !isDecoratorMemberExpression(\n node.type === \"CallExpression\" ? node.callee : node,\n );\n}\n\nexport function Decorator(this: Printer, node: t.Decorator) {\n this.token(\"@\");\n const { expression } = node;\n if (shouldParenthesizeDecoratorExpression(expression)) {\n this.token(\"(\");\n this.print(expression, node);\n this.token(\")\");\n } else {\n this.print(expression, node);\n }\n this.newline();\n}\n\nexport function OptionalMemberExpression(\n this: Printer,\n node: t.OptionalMemberExpression,\n) {\n this.print(node.object, node);\n\n if (!node.computed && isMemberExpression(node.property)) {\n throw new TypeError(\"Got a MemberExpression for MemberExpression property\");\n }\n\n let computed = node.computed;\n // @ts-expect-error todo(flow->ts) maybe instead of typeof check specific literal types?\n if (isLiteral(node.property) && typeof node.property.value === \"number\") {\n computed = true;\n }\n if (node.optional) {\n this.token(\"?.\");\n }\n\n if (computed) {\n this.token(\"[\");\n this.print(node.property, node);\n this.token(\"]\");\n } else {\n if (!node.optional) {\n this.token(\".\");\n }\n this.print(node.property, node);\n }\n}\n\nexport function OptionalCallExpression(\n this: Printer,\n node: t.OptionalCallExpression,\n) {\n this.print(node.callee, node);\n\n this.print(node.typeParameters, node); // TS\n\n if (node.optional) {\n this.token(\"?.\");\n }\n\n this.print(node.typeArguments, node); // Flow\n\n this.token(\"(\");\n this.printList(node.arguments, node);\n this.token(\")\");\n}\n\nexport function CallExpression(this: Printer, node: t.CallExpression) {\n this.print(node.callee, node);\n\n this.print(node.typeArguments, node); // Flow\n this.print(node.typeParameters, node); // TS\n this.token(\"(\");\n this.printList(node.arguments, node);\n this.token(\")\");\n}\n\nexport function Import(this: Printer) {\n this.word(\"import\");\n}\n\nexport function AwaitExpression(this: Printer, node: t.AwaitExpression) {\n this.word(\"await\");\n\n if (node.argument) {\n this.space();\n this.printTerminatorless(node.argument, node, false);\n }\n}\n\nexport function YieldExpression(this: Printer, node: t.YieldExpression) {\n this.word(\"yield\");\n\n if (node.delegate) {\n this.token(\"*\");\n }\n\n if (node.argument) {\n this.space();\n this.printTerminatorless(node.argument, node, false);\n }\n}\n\nexport function EmptyStatement(this: Printer) {\n this.semicolon(true /* force */);\n}\n\nexport function ExpressionStatement(\n this: Printer,\n node: t.ExpressionStatement,\n) {\n this.print(node.expression, node);\n this.semicolon();\n}\n\nexport function AssignmentPattern(this: Printer, node: t.AssignmentPattern) {\n this.print(node.left, node);\n // @ts-expect-error todo(flow->ts) property present on some of the types in union but not all\n if (node.left.optional) this.token(\"?\");\n // @ts-expect-error todo(flow->ts) property present on some of the types in union but not all\n this.print(node.left.typeAnnotation, node);\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.right, node);\n}\n\nexport function AssignmentExpression(\n this: Printer,\n node: t.AssignmentExpression,\n parent: t.Node,\n) {\n // Somewhere inside a for statement `init` node but doesn't usually\n // needs a paren except for `in` expressions: `for (a in b ? a : b;;)`\n const parens =\n this.inForStatementInitCounter &&\n node.operator === \"in\" &&\n !n.needsParens(node, parent);\n\n if (parens) {\n this.token(\"(\");\n }\n\n this.print(node.left, node);\n\n this.space();\n if (node.operator === \"in\" || node.operator === \"instanceof\") {\n this.word(node.operator);\n } else {\n this.token(node.operator);\n }\n this.space();\n\n this.print(node.right, node);\n\n if (parens) {\n this.token(\")\");\n }\n}\n\nexport function BindExpression(this: Printer, node: t.BindExpression) {\n this.print(node.object, node);\n this.token(\"::\");\n this.print(node.callee, node);\n}\n\nexport {\n AssignmentExpression as BinaryExpression,\n AssignmentExpression as LogicalExpression,\n};\n\nexport function MemberExpression(this: Printer, node: t.MemberExpression) {\n this.print(node.object, node);\n\n if (!node.computed && isMemberExpression(node.property)) {\n throw new TypeError(\"Got a MemberExpression for MemberExpression property\");\n }\n\n let computed = node.computed;\n // @ts-expect-error todo(flow->ts) maybe use specific literal types\n if (isLiteral(node.property) && typeof node.property.value === \"number\") {\n computed = true;\n }\n\n if (computed) {\n this.token(\"[\");\n this.print(node.property, node);\n this.token(\"]\");\n } else {\n this.token(\".\");\n this.print(node.property, node);\n }\n}\n\nexport function MetaProperty(this: Printer, node: t.MetaProperty) {\n this.print(node.meta, node);\n this.token(\".\");\n this.print(node.property, node);\n}\n\nexport function PrivateName(this: Printer, node: t.PrivateName) {\n this.token(\"#\");\n this.print(node.id, node);\n}\n\nexport function V8IntrinsicIdentifier(\n this: Printer,\n node: t.V8IntrinsicIdentifier,\n) {\n this.token(\"%\");\n this.word(node.name);\n}\n\nexport function ModuleExpression(this: Printer, node: t.ModuleExpression) {\n this.word(\"module\");\n // ensure no line terminator between `module` and `{`\n this.ensureNoLineTerminator(() => {\n this.printInnerComments(node);\n this.space();\n });\n this.token(\"{\");\n this.indent();\n const { body } = node;\n if (body.body.length || body.directives.length) {\n this.newline();\n }\n this.print(body, node);\n this.dedent();\n this.sourceWithOffset(\"end\", node.loc, 0, -1);\n this.rightBrace();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;;AAOA;;;EANEA,gB;EACAC,S;EACAC,kB;EACAC;;;AAKK,SAASC,eAAT,CAAwCC,IAAxC,EAAiE;EACtE,IACEA,IAAI,CAACC,QAAL,KAAkB,MAAlB,IACAD,IAAI,CAACC,QAAL,KAAkB,QADlB,IAEAD,IAAI,CAACC,QAAL,KAAkB,QAFlB,IAIAD,IAAI,CAACC,QAAL,KAAkB,OALpB,EAME;IACA,KAAKC,IAAL,CAAUF,IAAI,CAACC,QAAf;IACA,KAAKE,KAAL;EACD,CATD,MASO;IACL,KAAKC,KAAL,CAAWJ,IAAI,CAACC,QAAhB;EACD;;EAED,KAAKI,KAAL,CAAWL,IAAI,CAACM,QAAhB,EAA0BN,IAA1B;AACD;;AAEM,SAASO,YAAT,CAAqCP,IAArC,EAA2D;EAChE,IAAIA,IAAI,CAACQ,KAAT,EAAgB;IACd,KAAKN,IAAL,CAAU,OAAV;IACA,KAAKC,KAAL;EACD;;EACD,KAAKD,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A,KAAKC,KAAL,CAAWL,IAAI,CAACoE,EAAhB,EAAoBpE,IAApB;AACD;;AAEM,SAASqE,qBAAT,CAELrE,IAFK,EAGL;EACA,KAAKI,SAAL;EACA,KAAKF,IAAL,CAAUF,IAAI,CAACsE,IAAf;AACD;;AAEM,SAASC,gBAAT,CAAyCvE,IAAzC,EAAmE;EACxE,KAAKE,IAAL,CAAU,QAAV;EAEA,KAAKsE,sBAAL,CAA4B,MAAM;IAChC,KAAKC,kBAAL,CAAwBzE,IAAxB;IACA,KAAKG,KAAL;EACD,CAHD;EAIA,KAAKC,SAAL;EACA,KAAKsE,MAAL;EACA,MAAM;IAAEjE;EAAF,IAAWT,IAAjB;;EACA,IAAIS,IAAI,CAACA,IAAL,CAAUgB,MAAV,IAAoBhB,IAAI,CAACkE,UAAL,CAAgBlD,MAAxC,EAAgD;IAC9C,KAAKgB,OAAL;EACD;;EACD,KAAKpC,KAAL,CAAWI,IAAX,EAAiBT,IAAjB;EACA,KAAK4E,MAAL;EACA,KAAKC,gBAAL,CAAsB,KAAtB,EAA6B7E,IAAI,CAAC8E,GAAlC,EAAuC,CAAvC,EAA0C,CAAC,CAA3C;EACA,KAAKC,UAAL;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/flow.js b/node_modules/@babel/generator/lib/generators/flow.js new file mode 100644 index 0000000..26fa97f --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/flow.js @@ -0,0 +1,798 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.AnyTypeAnnotation = AnyTypeAnnotation; +exports.ArrayTypeAnnotation = ArrayTypeAnnotation; +exports.BooleanLiteralTypeAnnotation = BooleanLiteralTypeAnnotation; +exports.BooleanTypeAnnotation = BooleanTypeAnnotation; +exports.DeclareClass = DeclareClass; +exports.DeclareExportAllDeclaration = DeclareExportAllDeclaration; +exports.DeclareExportDeclaration = DeclareExportDeclaration; +exports.DeclareFunction = DeclareFunction; +exports.DeclareInterface = DeclareInterface; +exports.DeclareModule = DeclareModule; +exports.DeclareModuleExports = DeclareModuleExports; +exports.DeclareOpaqueType = DeclareOpaqueType; +exports.DeclareTypeAlias = DeclareTypeAlias; +exports.DeclareVariable = DeclareVariable; +exports.DeclaredPredicate = DeclaredPredicate; +exports.EmptyTypeAnnotation = EmptyTypeAnnotation; +exports.EnumBooleanBody = EnumBooleanBody; +exports.EnumBooleanMember = EnumBooleanMember; +exports.EnumDeclaration = EnumDeclaration; +exports.EnumDefaultedMember = EnumDefaultedMember; +exports.EnumNumberBody = EnumNumberBody; +exports.EnumNumberMember = EnumNumberMember; +exports.EnumStringBody = EnumStringBody; +exports.EnumStringMember = EnumStringMember; +exports.EnumSymbolBody = EnumSymbolBody; +exports.ExistsTypeAnnotation = ExistsTypeAnnotation; +exports.FunctionTypeAnnotation = FunctionTypeAnnotation; +exports.FunctionTypeParam = FunctionTypeParam; +exports.IndexedAccessType = IndexedAccessType; +exports.InferredPredicate = InferredPredicate; +exports.InterfaceDeclaration = InterfaceDeclaration; +exports.GenericTypeAnnotation = exports.ClassImplements = exports.InterfaceExtends = InterfaceExtends; +exports.InterfaceTypeAnnotation = InterfaceTypeAnnotation; +exports.IntersectionTypeAnnotation = IntersectionTypeAnnotation; +exports.MixedTypeAnnotation = MixedTypeAnnotation; +exports.NullLiteralTypeAnnotation = NullLiteralTypeAnnotation; +exports.NullableTypeAnnotation = NullableTypeAnnotation; +Object.defineProperty(exports, "NumberLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _types2.NumericLiteral; + } +}); +exports.NumberTypeAnnotation = NumberTypeAnnotation; +exports.ObjectTypeAnnotation = ObjectTypeAnnotation; +exports.ObjectTypeCallProperty = ObjectTypeCallProperty; +exports.ObjectTypeIndexer = ObjectTypeIndexer; +exports.ObjectTypeInternalSlot = ObjectTypeInternalSlot; +exports.ObjectTypeProperty = ObjectTypeProperty; +exports.ObjectTypeSpreadProperty = ObjectTypeSpreadProperty; +exports.OpaqueType = OpaqueType; +exports.OptionalIndexedAccessType = OptionalIndexedAccessType; +exports.QualifiedTypeIdentifier = QualifiedTypeIdentifier; +Object.defineProperty(exports, "StringLiteralTypeAnnotation", { + enumerable: true, + get: function () { + return _types2.StringLiteral; + } +}); +exports.StringTypeAnnotation = StringTypeAnnotation; +exports.SymbolTypeAnnotation = SymbolTypeAnnotation; +exports.ThisTypeAnnotation = ThisTypeAnnotation; +exports.TupleTypeAnnotation = TupleTypeAnnotation; +exports.TypeAlias = TypeAlias; +exports.TypeAnnotation = TypeAnnotation; +exports.TypeCastExpression = TypeCastExpression; +exports.TypeParameter = TypeParameter; +exports.TypeParameterDeclaration = exports.TypeParameterInstantiation = TypeParameterInstantiation; +exports.TypeofTypeAnnotation = TypeofTypeAnnotation; +exports.UnionTypeAnnotation = UnionTypeAnnotation; +exports.Variance = Variance; +exports.VoidTypeAnnotation = VoidTypeAnnotation; +exports._interfaceish = _interfaceish; +exports._variance = _variance; + +var _t = require("@babel/types"); + +var _modules = require("./modules"); + +var _types2 = require("./types"); + +const { + isDeclareExportDeclaration, + isStatement +} = _t; + +function AnyTypeAnnotation() { + this.word("any"); +} + +function ArrayTypeAnnotation(node) { + this.print(node.elementType, node, true); + this.tokenChar(91); + this.tokenChar(93); +} + +function BooleanTypeAnnotation() { + this.word("boolean"); +} + +function BooleanLiteralTypeAnnotation(node) { + this.word(node.value ? "true" : "false"); +} + +function NullLiteralTypeAnnotation() { + this.word("null"); +} + +function DeclareClass(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + + this.word("class"); + this.space(); + + this._interfaceish(node); +} + +function DeclareFunction(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + + this.word("function"); + this.space(); + this.print(node.id, node); + this.print(node.id.typeAnnotation.typeAnnotation, node); + + if (node.predicate) { + this.space(); + this.print(node.predicate, node); + } + + this.semicolon(); +} + +function InferredPredicate() { + this.tokenChar(37); + this.word("checks"); +} + +function DeclaredPredicate(node) { + this.tokenChar(37); + this.word("checks"); + this.tokenChar(40); + this.print(node.value, node); + this.tokenChar(41); +} + +function DeclareInterface(node) { + this.word("declare"); + this.space(); + this.InterfaceDeclaration(node); +} + +function DeclareModule(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.space(); + this.print(node.id, node); + this.space(); + this.print(node.body, node); +} + +function DeclareModuleExports(node) { + this.word("declare"); + this.space(); + this.word("module"); + this.tokenChar(46); + this.word("exports"); + this.print(node.typeAnnotation, node); +} + +function DeclareTypeAlias(node) { + this.word("declare"); + this.space(); + this.TypeAlias(node); +} + +function DeclareOpaqueType(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + + this.OpaqueType(node); +} + +function DeclareVariable(node, parent) { + if (!isDeclareExportDeclaration(parent)) { + this.word("declare"); + this.space(); + } + + this.word("var"); + this.space(); + this.print(node.id, node); + this.print(node.id.typeAnnotation, node); + this.semicolon(); +} + +function DeclareExportDeclaration(node) { + this.word("declare"); + this.space(); + this.word("export"); + this.space(); + + if (node.default) { + this.word("default"); + this.space(); + } + + FlowExportDeclaration.call(this, node); +} + +function DeclareExportAllDeclaration(node) { + this.word("declare"); + this.space(); + + _modules.ExportAllDeclaration.call(this, node); +} + +function EnumDeclaration(node) { + const { + id, + body + } = node; + this.word("enum"); + this.space(); + this.print(id, node); + this.print(body, node); +} + +function enumExplicitType(context, name, hasExplicitType) { + if (hasExplicitType) { + context.space(); + context.word("of"); + context.space(); + context.word(name); + } + + context.space(); +} + +function enumBody(context, node) { + const { + members + } = node; + context.token("{"); + context.indent(); + context.newline(); + + for (const member of members) { + context.print(member, node); + context.newline(); + } + + if (node.hasUnknownMembers) { + context.token("..."); + context.newline(); + } + + context.dedent(); + context.token("}"); +} + +function EnumBooleanBody(node) { + const { + explicitType + } = node; + enumExplicitType(this, "boolean", explicitType); + enumBody(this, node); +} + +function EnumNumberBody(node) { + const { + explicitType + } = node; + enumExplicitType(this, "number", explicitType); + enumBody(this, node); +} + +function EnumStringBody(node) { + const { + explicitType + } = node; + enumExplicitType(this, "string", explicitType); + enumBody(this, node); +} + +function EnumSymbolBody(node) { + enumExplicitType(this, "symbol", true); + enumBody(this, node); +} + +function EnumDefaultedMember(node) { + const { + id + } = node; + this.print(id, node); + this.tokenChar(44); +} + +function enumInitializedMember(context, node) { + const { + id, + init + } = node; + context.print(id, node); + context.space(); + context.token("="); + context.space(); + context.print(init, node); + context.token(","); +} + +function EnumBooleanMember(node) { + enumInitializedMember(this, node); +} + +function EnumNumberMember(node) { + enumInitializedMember(this, node); +} + +function EnumStringMember(node) { + enumInitializedMember(this, node); +} + +function FlowExportDeclaration(node) { + if (node.declaration) { + const declar = node.declaration; + this.print(declar, node); + if (!isStatement(declar)) this.semicolon(); + } else { + this.tokenChar(123); + + if (node.specifiers.length) { + this.space(); + this.printList(node.specifiers, node); + this.space(); + } + + this.tokenChar(125); + + if (node.source) { + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + } + + this.semicolon(); + } +} + +function ExistsTypeAnnotation() { + this.tokenChar(42); +} + +function FunctionTypeAnnotation(node, parent) { + this.print(node.typeParameters, node); + this.tokenChar(40); + + if (node.this) { + this.word("this"); + this.tokenChar(58); + this.space(); + this.print(node.this.typeAnnotation, node); + + if (node.params.length || node.rest) { + this.tokenChar(44); + this.space(); + } + } + + this.printList(node.params, node); + + if (node.rest) { + if (node.params.length) { + this.tokenChar(44); + this.space(); + } + + this.token("..."); + this.print(node.rest, node); + } + + this.tokenChar(41); + + if (parent && (parent.type === "ObjectTypeCallProperty" || parent.type === "ObjectTypeInternalSlot" || parent.type === "DeclareFunction" || parent.type === "ObjectTypeProperty" && parent.method)) { + this.tokenChar(58); + } else { + this.space(); + this.token("=>"); + } + + this.space(); + this.print(node.returnType, node); +} + +function FunctionTypeParam(node) { + this.print(node.name, node); + if (node.optional) this.tokenChar(63); + + if (node.name) { + this.tokenChar(58); + this.space(); + } + + this.print(node.typeAnnotation, node); +} + +function InterfaceExtends(node) { + this.print(node.id, node); + this.print(node.typeParameters, node, true); +} + +function _interfaceish(node) { + var _node$extends; + + this.print(node.id, node); + this.print(node.typeParameters, node); + + if ((_node$extends = node.extends) != null && _node$extends.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(node.extends, node); + } + + if (node.mixins && node.mixins.length) { + this.space(); + this.word("mixins"); + this.space(); + this.printList(node.mixins, node); + } + + if (node.implements && node.implements.length) { + this.space(); + this.word("implements"); + this.space(); + this.printList(node.implements, node); + } + + this.space(); + this.print(node.body, node); +} + +function _variance(node) { + if (node.variance) { + if (node.variance.kind === "plus") { + this.tokenChar(43); + } else if (node.variance.kind === "minus") { + this.tokenChar(45); + } + } +} + +function InterfaceDeclaration(node) { + this.word("interface"); + this.space(); + + this._interfaceish(node); +} + +function andSeparator() { + this.space(); + this.tokenChar(38); + this.space(); +} + +function InterfaceTypeAnnotation(node) { + this.word("interface"); + + if (node.extends && node.extends.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(node.extends, node); + } + + this.space(); + this.print(node.body, node); +} + +function IntersectionTypeAnnotation(node) { + this.printJoin(node.types, node, { + separator: andSeparator + }); +} + +function MixedTypeAnnotation() { + this.word("mixed"); +} + +function EmptyTypeAnnotation() { + this.word("empty"); +} + +function NullableTypeAnnotation(node) { + this.tokenChar(63); + this.print(node.typeAnnotation, node); +} + +function NumberTypeAnnotation() { + this.word("number"); +} + +function StringTypeAnnotation() { + this.word("string"); +} + +function ThisTypeAnnotation() { + this.word("this"); +} + +function TupleTypeAnnotation(node) { + this.tokenChar(91); + this.printList(node.types, node); + this.tokenChar(93); +} + +function TypeofTypeAnnotation(node) { + this.word("typeof"); + this.space(); + this.print(node.argument, node); +} + +function TypeAlias(node) { + this.word("type"); + this.space(); + this.print(node.id, node); + this.print(node.typeParameters, node); + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.right, node); + this.semicolon(); +} + +function TypeAnnotation(node) { + this.tokenChar(58); + this.space(); + if (node.optional) this.tokenChar(63); + this.print(node.typeAnnotation, node); +} + +function TypeParameterInstantiation(node) { + this.tokenChar(60); + this.printList(node.params, node, {}); + this.tokenChar(62); +} + +function TypeParameter(node) { + this._variance(node); + + this.word(node.name); + + if (node.bound) { + this.print(node.bound, node); + } + + if (node.default) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.default, node); + } +} + +function OpaqueType(node) { + this.word("opaque"); + this.space(); + this.word("type"); + this.space(); + this.print(node.id, node); + this.print(node.typeParameters, node); + + if (node.supertype) { + this.tokenChar(58); + this.space(); + this.print(node.supertype, node); + } + + if (node.impltype) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.impltype, node); + } + + this.semicolon(); +} + +function ObjectTypeAnnotation(node) { + if (node.exact) { + this.token("{|"); + } else { + this.tokenChar(123); + } + + const props = [...node.properties, ...(node.callProperties || []), ...(node.indexers || []), ...(node.internalSlots || [])]; + + if (props.length) { + this.newline(); + this.space(); + this.printJoin(props, node, { + addNewlines(leading) { + if (leading && !props[0]) return 1; + }, + + indent: true, + statement: true, + iterator: () => { + if (props.length !== 1 || node.inexact) { + this.tokenChar(44); + this.space(); + } + } + }); + this.space(); + } + + if (node.inexact) { + this.indent(); + this.token("..."); + + if (props.length) { + this.newline(); + } + + this.dedent(); + } + + if (node.exact) { + this.token("|}"); + } else { + this.tokenChar(125); + } +} + +function ObjectTypeInternalSlot(node) { + if (node.static) { + this.word("static"); + this.space(); + } + + this.tokenChar(91); + this.tokenChar(91); + this.print(node.id, node); + this.tokenChar(93); + this.tokenChar(93); + if (node.optional) this.tokenChar(63); + + if (!node.method) { + this.tokenChar(58); + this.space(); + } + + this.print(node.value, node); +} + +function ObjectTypeCallProperty(node) { + if (node.static) { + this.word("static"); + this.space(); + } + + this.print(node.value, node); +} + +function ObjectTypeIndexer(node) { + if (node.static) { + this.word("static"); + this.space(); + } + + this._variance(node); + + this.tokenChar(91); + + if (node.id) { + this.print(node.id, node); + this.tokenChar(58); + this.space(); + } + + this.print(node.key, node); + this.tokenChar(93); + this.tokenChar(58); + this.space(); + this.print(node.value, node); +} + +function ObjectTypeProperty(node) { + if (node.proto) { + this.word("proto"); + this.space(); + } + + if (node.static) { + this.word("static"); + this.space(); + } + + if (node.kind === "get" || node.kind === "set") { + this.word(node.kind); + this.space(); + } + + this._variance(node); + + this.print(node.key, node); + if (node.optional) this.tokenChar(63); + + if (!node.method) { + this.tokenChar(58); + this.space(); + } + + this.print(node.value, node); +} + +function ObjectTypeSpreadProperty(node) { + this.token("..."); + this.print(node.argument, node); +} + +function QualifiedTypeIdentifier(node) { + this.print(node.qualification, node); + this.tokenChar(46); + this.print(node.id, node); +} + +function SymbolTypeAnnotation() { + this.word("symbol"); +} + +function orSeparator() { + this.space(); + this.tokenChar(124); + this.space(); +} + +function UnionTypeAnnotation(node) { + this.printJoin(node.types, node, { + separator: orSeparator + }); +} + +function TypeCastExpression(node) { + this.tokenChar(40); + this.print(node.expression, node); + this.print(node.typeAnnotation, node); + this.tokenChar(41); +} + +function Variance(node) { + if (node.kind === "plus") { + this.tokenChar(43); + } else { + this.tokenChar(45); + } +} + +function VoidTypeAnnotation() { + this.word("void"); +} + +function IndexedAccessType(node) { + this.print(node.objectType, node, true); + this.tokenChar(91); + this.print(node.indexType, node); + this.tokenChar(93); +} + +function OptionalIndexedAccessType(node) { + this.print(node.objectType, node); + + if (node.optional) { + this.token("?."); + } + + this.tokenChar(91); + this.print(node.indexType, node); + this.tokenChar(93); +} + +//# sourceMappingURL=flow.js.map diff --git a/node_modules/@babel/generator/lib/generators/flow.js.map b/node_modules/@babel/generator/lib/generators/flow.js.map new file mode 100644 index 0000000..64a947e --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/flow.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isDeclareExportDeclaration","isStatement","AnyTypeAnnotation","word","ArrayTypeAnnotation","node","print","elementType","token","BooleanTypeAnnotation","BooleanLiteralTypeAnnotation","value","NullLiteralTypeAnnotation","DeclareClass","parent","space","_interfaceish","DeclareFunction","id","typeAnnotation","predicate","semicolon","InferredPredicate","DeclaredPredicate","DeclareInterface","InterfaceDeclaration","DeclareModule","body","DeclareModuleExports","DeclareTypeAlias","TypeAlias","DeclareOpaqueType","OpaqueType","DeclareVariable","DeclareExportDeclaration","default","FlowExportDeclaration","call","DeclareExportAllDeclaration","ExportAllDeclaration","EnumDeclaration","enumExplicitType","context","name","hasExplicitType","enumBody","members","indent","newline","member","hasUnknownMembers","dedent","EnumBooleanBody","explicitType","EnumNumberBody","EnumStringBody","EnumSymbolBody","EnumDefaultedMember","enumInitializedMember","init","EnumBooleanMember","EnumNumberMember","EnumStringMember","declaration","declar","specifiers","length","printList","source","ExistsTypeAnnotation","FunctionTypeAnnotation","typeParameters","this","params","rest","type","method","returnType","FunctionTypeParam","optional","InterfaceExtends","extends","mixins","implements","_variance","variance","kind","andSeparator","InterfaceTypeAnnotation","IntersectionTypeAnnotation","printJoin","types","separator","MixedTypeAnnotation","EmptyTypeAnnotation","NullableTypeAnnotation","NumberTypeAnnotation","StringTypeAnnotation","ThisTypeAnnotation","TupleTypeAnnotation","TypeofTypeAnnotation","argument","right","TypeAnnotation","TypeParameterInstantiation","TypeParameter","bound","supertype","impltype","ObjectTypeAnnotation","exact","props","properties","callProperties","indexers","internalSlots","addNewlines","leading","statement","iterator","inexact","ObjectTypeInternalSlot","static","ObjectTypeCallProperty","ObjectTypeIndexer","key","ObjectTypeProperty","proto","ObjectTypeSpreadProperty","QualifiedTypeIdentifier","qualification","SymbolTypeAnnotation","orSeparator","UnionTypeAnnotation","TypeCastExpression","expression","Variance","VoidTypeAnnotation","IndexedAccessType","objectType","indexType","OptionalIndexedAccessType"],"sources":["../../src/generators/flow.ts"],"sourcesContent":["import type Printer from \"../printer\";\nimport { isDeclareExportDeclaration, isStatement } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport { ExportAllDeclaration } from \"./modules\";\n\nexport function AnyTypeAnnotation(this: Printer) {\n this.word(\"any\");\n}\n\nexport function ArrayTypeAnnotation(\n this: Printer,\n node: t.ArrayTypeAnnotation,\n) {\n this.print(node.elementType, node, true);\n this.token(\"[\");\n this.token(\"]\");\n}\n\nexport function BooleanTypeAnnotation(this: Printer) {\n this.word(\"boolean\");\n}\n\nexport function BooleanLiteralTypeAnnotation(\n this: Printer,\n node: t.BooleanLiteralTypeAnnotation,\n) {\n this.word(node.value ? \"true\" : \"false\");\n}\n\nexport function NullLiteralTypeAnnotation(this: Printer) {\n this.word(\"null\");\n}\n\nexport function DeclareClass(\n this: Printer,\n node: t.DeclareClass,\n parent: t.Node,\n) {\n if (!isDeclareExportDeclaration(parent)) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"class\");\n this.space();\n this._interfaceish(node);\n}\n\nexport function DeclareFunction(\n this: Printer,\n node: t.DeclareFunction,\n parent: t.Node,\n) {\n if (!isDeclareExportDeclaration(parent)) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"function\");\n this.space();\n this.print(node.id, node);\n // @ts-ignore(Babel 7 vs Babel 8) TODO(Babel 8) Remove this comment, since we'll remove the Noop node\n this.print(node.id.typeAnnotation.typeAnnotation, node);\n\n if (node.predicate) {\n this.space();\n this.print(node.predicate, node);\n }\n\n this.semicolon();\n}\n\nexport function InferredPredicate(this: Printer) {\n this.token(\"%\");\n this.word(\"checks\");\n}\n\nexport function DeclaredPredicate(this: Printer, node: t.DeclaredPredicate) {\n this.token(\"%\");\n this.word(\"checks\");\n this.token(\"(\");\n this.print(node.value, node);\n this.token(\")\");\n}\n\nexport function DeclareInterface(this: Printer, node: t.DeclareInterface) {\n this.word(\"declare\");\n this.space();\n this.InterfaceDeclaration(node);\n}\n\nexport function DeclareModule(this: Printer, node: t.DeclareModule) {\n this.word(\"declare\");\n this.space();\n this.word(\"module\");\n this.space();\n this.print(node.id, node);\n this.space();\n this.print(node.body, node);\n}\n\nexport function DeclareModuleExports(\n this: Printer,\n node: t.DeclareModuleExports,\n) {\n this.word(\"declare\");\n this.space();\n this.word(\"module\");\n this.token(\".\");\n this.word(\"exports\");\n this.print(node.typeAnnotation, node);\n}\n\nexport function DeclareTypeAlias(this: Printer, node: t.DeclareTypeAlias) {\n this.word(\"declare\");\n this.space();\n this.TypeAlias(node);\n}\n\nexport function DeclareOpaqueType(\n this: Printer,\n node: t.DeclareOpaqueType,\n parent: t.Node,\n) {\n if (!isDeclareExportDeclaration(parent)) {\n this.word(\"declare\");\n this.space();\n }\n this.OpaqueType(node);\n}\n\nexport function DeclareVariable(\n this: Printer,\n node: t.DeclareVariable,\n parent: t.Node,\n) {\n if (!isDeclareExportDeclaration(parent)) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"var\");\n this.space();\n this.print(node.id, node);\n this.print(node.id.typeAnnotation, node);\n this.semicolon();\n}\n\nexport function DeclareExportDeclaration(\n this: Printer,\n node: t.DeclareExportDeclaration,\n) {\n this.word(\"declare\");\n this.space();\n this.word(\"export\");\n this.space();\n if (node.default) {\n this.word(\"default\");\n this.space();\n }\n\n FlowExportDeclaration.call(this, node);\n}\n\nexport function DeclareExportAllDeclaration(\n this: Printer,\n node: t.DeclareExportAllDeclaration,\n) {\n this.word(\"declare\");\n this.space();\n ExportAllDeclaration.call(this, node);\n}\n\nexport function EnumDeclaration(this: Printer, node: t.EnumDeclaration) {\n const { id, body } = node;\n this.word(\"enum\");\n this.space();\n this.print(id, node);\n this.print(body, node);\n}\n\nfunction enumExplicitType(\n context: Printer,\n name: string,\n hasExplicitType: boolean,\n) {\n if (hasExplicitType) {\n context.space();\n context.word(\"of\");\n context.space();\n context.word(name);\n }\n context.space();\n}\n\nfunction enumBody(context: Printer, node: t.EnumBody) {\n const { members } = node;\n context.token(\"{\");\n context.indent();\n context.newline();\n for (const member of members) {\n context.print(member, node);\n context.newline();\n }\n if (node.hasUnknownMembers) {\n context.token(\"...\");\n context.newline();\n }\n context.dedent();\n context.token(\"}\");\n}\n\nexport function EnumBooleanBody(this: Printer, node: t.EnumBooleanBody) {\n const { explicitType } = node;\n enumExplicitType(this, \"boolean\", explicitType);\n enumBody(this, node);\n}\n\nexport function EnumNumberBody(this: Printer, node: t.EnumNumberBody) {\n const { explicitType } = node;\n enumExplicitType(this, \"number\", explicitType);\n enumBody(this, node);\n}\n\nexport function EnumStringBody(this: Printer, node: t.EnumStringBody) {\n const { explicitType } = node;\n enumExplicitType(this, \"string\", explicitType);\n enumBody(this, node);\n}\n\nexport function EnumSymbolBody(this: Printer, node: t.EnumSymbolBody) {\n enumExplicitType(this, \"symbol\", true);\n enumBody(this, node);\n}\n\nexport function EnumDefaultedMember(\n this: Printer,\n node: t.EnumDefaultedMember,\n) {\n const { id } = node;\n this.print(id, node);\n this.token(\",\");\n}\n\nfunction enumInitializedMember(\n context: Printer,\n node: t.EnumBooleanMember | t.EnumNumberMember | t.EnumStringMember,\n) {\n const { id, init } = node;\n context.print(id, node);\n context.space();\n context.token(\"=\");\n context.space();\n context.print(init, node);\n context.token(\",\");\n}\n\nexport function EnumBooleanMember(this: Printer, node: t.EnumBooleanMember) {\n enumInitializedMember(this, node);\n}\n\nexport function EnumNumberMember(this: Printer, node: t.EnumNumberMember) {\n enumInitializedMember(this, node);\n}\n\nexport function EnumStringMember(this: Printer, node: t.EnumStringMember) {\n enumInitializedMember(this, node);\n}\n\nfunction FlowExportDeclaration(\n this: Printer,\n node: t.DeclareExportDeclaration,\n) {\n if (node.declaration) {\n const declar = node.declaration;\n this.print(declar, node);\n if (!isStatement(declar)) this.semicolon();\n } else {\n this.token(\"{\");\n if (node.specifiers.length) {\n this.space();\n this.printList(node.specifiers, node);\n this.space();\n }\n this.token(\"}\");\n\n if (node.source) {\n this.space();\n this.word(\"from\");\n this.space();\n this.print(node.source, node);\n }\n\n this.semicolon();\n }\n}\n\nexport function ExistsTypeAnnotation(this: Printer) {\n this.token(\"*\");\n}\n\nexport function FunctionTypeAnnotation(\n this: Printer,\n node: t.FunctionTypeAnnotation,\n parent: t.Node | void,\n) {\n this.print(node.typeParameters, node);\n this.token(\"(\");\n\n if (node.this) {\n this.word(\"this\");\n this.token(\":\");\n this.space();\n this.print(node.this.typeAnnotation, node);\n if (node.params.length || node.rest) {\n this.token(\",\");\n this.space();\n }\n }\n\n this.printList(node.params, node);\n\n if (node.rest) {\n if (node.params.length) {\n this.token(\",\");\n this.space();\n }\n this.token(\"...\");\n this.print(node.rest, node);\n }\n\n this.token(\")\");\n\n // this node type is overloaded, not sure why but it makes it EXTREMELY annoying\n if (\n parent &&\n (parent.type === \"ObjectTypeCallProperty\" ||\n parent.type === \"ObjectTypeInternalSlot\" ||\n parent.type === \"DeclareFunction\" ||\n (parent.type === \"ObjectTypeProperty\" && parent.method))\n ) {\n this.token(\":\");\n } else {\n this.space();\n this.token(\"=>\");\n }\n\n this.space();\n this.print(node.returnType, node);\n}\n\nexport function FunctionTypeParam(this: Printer, node: t.FunctionTypeParam) {\n this.print(node.name, node);\n if (node.optional) this.token(\"?\");\n if (node.name) {\n this.token(\":\");\n this.space();\n }\n this.print(node.typeAnnotation, node);\n}\n\nexport function InterfaceExtends(this: Printer, node: t.InterfaceExtends) {\n this.print(node.id, node);\n this.print(node.typeParameters, node, true);\n}\n\nexport {\n InterfaceExtends as ClassImplements,\n InterfaceExtends as GenericTypeAnnotation,\n};\n\nexport function _interfaceish(\n this: Printer,\n node: t.InterfaceDeclaration | t.DeclareInterface | t.DeclareClass,\n) {\n this.print(node.id, node);\n this.print(node.typeParameters, node);\n if (node.extends?.length) {\n this.space();\n this.word(\"extends\");\n this.space();\n this.printList(node.extends, node);\n }\n if (node.mixins && node.mixins.length) {\n this.space();\n this.word(\"mixins\");\n this.space();\n this.printList(node.mixins, node);\n }\n if (node.implements && node.implements.length) {\n this.space();\n this.word(\"implements\");\n this.space();\n this.printList(node.implements, node);\n }\n this.space();\n this.print(node.body, node);\n}\n\nexport function _variance(\n this: Printer,\n node:\n | t.TypeParameter\n | t.ObjectTypeIndexer\n | t.ObjectTypeProperty\n | t.ClassProperty\n | t.ClassPrivateProperty\n | t.ClassAccessorProperty,\n) {\n if (node.variance) {\n if (node.variance.kind === \"plus\") {\n this.token(\"+\");\n } else if (node.variance.kind === \"minus\") {\n this.token(\"-\");\n }\n }\n}\n\nexport function InterfaceDeclaration(\n this: Printer,\n node: t.InterfaceDeclaration | t.DeclareInterface,\n) {\n this.word(\"interface\");\n this.space();\n this._interfaceish(node);\n}\n\nfunction andSeparator(this: Printer) {\n this.space();\n this.token(\"&\");\n this.space();\n}\n\nexport function InterfaceTypeAnnotation(\n this: Printer,\n node: t.InterfaceTypeAnnotation,\n) {\n this.word(\"interface\");\n if (node.extends && node.extends.length) {\n this.space();\n this.word(\"extends\");\n this.space();\n this.printList(node.extends, node);\n }\n this.space();\n this.print(node.body, node);\n}\n\nexport function IntersectionTypeAnnotation(\n this: Printer,\n node: t.IntersectionTypeAnnotation,\n) {\n this.printJoin(node.types, node, { separator: andSeparator });\n}\n\nexport function MixedTypeAnnotation(this: Printer) {\n this.word(\"mixed\");\n}\n\nexport function EmptyTypeAnnotation(this: Printer) {\n this.word(\"empty\");\n}\n\nexport function NullableTypeAnnotation(\n this: Printer,\n node: t.NullableTypeAnnotation,\n) {\n this.token(\"?\");\n this.print(node.typeAnnotation, node);\n}\n\nexport {\n NumericLiteral as NumberLiteralTypeAnnotation,\n StringLiteral as StringLiteralTypeAnnotation,\n} from \"./types\";\n\nexport function NumberTypeAnnotation(this: Printer) {\n this.word(\"number\");\n}\n\nexport function StringTypeAnnotation(this: Printer) {\n this.word(\"string\");\n}\n\nexport function ThisTypeAnnotation(this: Printer) {\n this.word(\"this\");\n}\n\nexport function TupleTypeAnnotation(\n this: Printer,\n node: t.TupleTypeAnnotation,\n) {\n this.token(\"[\");\n this.printList(node.types, node);\n this.token(\"]\");\n}\n\nexport function TypeofTypeAnnotation(\n this: Printer,\n node: t.TypeofTypeAnnotation,\n) {\n this.word(\"typeof\");\n this.space();\n this.print(node.argument, node);\n}\n\nexport function TypeAlias(\n this: Printer,\n node: t.TypeAlias | t.DeclareTypeAlias,\n) {\n this.word(\"type\");\n this.space();\n this.print(node.id, node);\n this.print(node.typeParameters, node);\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.right, node);\n this.semicolon();\n}\n\nexport function TypeAnnotation(this: Printer, node: t.TypeAnnotation) {\n this.token(\":\");\n this.space();\n // @ts-expect-error todo(flow->ts) can this be removed? `.optional` looks to be not existing property\n if (node.optional) this.token(\"?\");\n this.print(node.typeAnnotation, node);\n}\n\nexport function TypeParameterInstantiation(\n this: Printer,\n node: t.TypeParameterInstantiation,\n): void {\n this.token(\"<\");\n this.printList(node.params, node, {});\n this.token(\">\");\n}\n\nexport { TypeParameterInstantiation as TypeParameterDeclaration };\n\nexport function TypeParameter(this: Printer, node: t.TypeParameter) {\n this._variance(node);\n\n this.word(node.name);\n\n if (node.bound) {\n this.print(node.bound, node);\n }\n\n if (node.default) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.default, node);\n }\n}\n\nexport function OpaqueType(\n this: Printer,\n node: t.OpaqueType | t.DeclareOpaqueType,\n) {\n this.word(\"opaque\");\n this.space();\n this.word(\"type\");\n this.space();\n this.print(node.id, node);\n this.print(node.typeParameters, node);\n if (node.supertype) {\n this.token(\":\");\n this.space();\n this.print(node.supertype, node);\n }\n\n if (node.impltype) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.impltype, node);\n }\n this.semicolon();\n}\n\nexport function ObjectTypeAnnotation(\n this: Printer,\n node: t.ObjectTypeAnnotation,\n) {\n if (node.exact) {\n this.token(\"{|\");\n } else {\n this.token(\"{\");\n }\n\n // TODO: remove the array fallbacks and instead enforce the types to require an array\n const props = [\n ...node.properties,\n ...(node.callProperties || []),\n ...(node.indexers || []),\n ...(node.internalSlots || []),\n ];\n\n if (props.length) {\n this.newline();\n\n this.space();\n\n this.printJoin(props, node, {\n addNewlines(leading) {\n if (leading && !props[0]) return 1;\n },\n indent: true,\n statement: true,\n iterator: () => {\n if (props.length !== 1 || node.inexact) {\n this.token(\",\");\n this.space();\n }\n },\n });\n\n this.space();\n }\n\n if (node.inexact) {\n this.indent();\n this.token(\"...\");\n if (props.length) {\n this.newline();\n }\n this.dedent();\n }\n\n if (node.exact) {\n this.token(\"|}\");\n } else {\n this.token(\"}\");\n }\n}\n\nexport function ObjectTypeInternalSlot(\n this: Printer,\n node: t.ObjectTypeInternalSlot,\n) {\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n this.token(\"[\");\n this.token(\"[\");\n this.print(node.id, node);\n this.token(\"]\");\n this.token(\"]\");\n if (node.optional) this.token(\"?\");\n if (!node.method) {\n this.token(\":\");\n this.space();\n }\n this.print(node.value, node);\n}\n\nexport function ObjectTypeCallProperty(\n this: Printer,\n node: t.ObjectTypeCallProperty,\n) {\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n this.print(node.value, node);\n}\n\nexport function ObjectTypeIndexer(this: Printer, node: t.ObjectTypeIndexer) {\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n this._variance(node);\n this.token(\"[\");\n if (node.id) {\n this.print(node.id, node);\n this.token(\":\");\n this.space();\n }\n this.print(node.key, node);\n this.token(\"]\");\n this.token(\":\");\n this.space();\n this.print(node.value, node);\n}\n\nexport function ObjectTypeProperty(this: Printer, node: t.ObjectTypeProperty) {\n if (node.proto) {\n this.word(\"proto\");\n this.space();\n }\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n if (node.kind === \"get\" || node.kind === \"set\") {\n this.word(node.kind);\n this.space();\n }\n this._variance(node);\n this.print(node.key, node);\n if (node.optional) this.token(\"?\");\n if (!node.method) {\n this.token(\":\");\n this.space();\n }\n this.print(node.value, node);\n}\n\nexport function ObjectTypeSpreadProperty(\n this: Printer,\n node: t.ObjectTypeSpreadProperty,\n) {\n this.token(\"...\");\n this.print(node.argument, node);\n}\n\nexport function QualifiedTypeIdentifier(\n this: Printer,\n node: t.QualifiedTypeIdentifier,\n) {\n this.print(node.qualification, node);\n this.token(\".\");\n this.print(node.id, node);\n}\n\nexport function SymbolTypeAnnotation(this: Printer) {\n this.word(\"symbol\");\n}\n\nfunction orSeparator(this: Printer) {\n this.space();\n this.token(\"|\");\n this.space();\n}\n\nexport function UnionTypeAnnotation(\n this: Printer,\n node: t.UnionTypeAnnotation,\n) {\n this.printJoin(node.types, node, { separator: orSeparator });\n}\n\nexport function TypeCastExpression(this: Printer, node: t.TypeCastExpression) {\n this.token(\"(\");\n this.print(node.expression, node);\n this.print(node.typeAnnotation, node);\n this.token(\")\");\n}\n\nexport function Variance(this: Printer, node: t.Variance) {\n if (node.kind === \"plus\") {\n this.token(\"+\");\n } else {\n this.token(\"-\");\n }\n}\n\nexport function VoidTypeAnnotation(this: Printer) {\n this.word(\"void\");\n}\n\nexport function IndexedAccessType(this: Printer, node: t.IndexedAccessType) {\n this.print(node.objectType, node, true);\n this.token(\"[\");\n this.print(node.indexType, node);\n this.token(\"]\");\n}\n\nexport function OptionalIndexedAccessType(\n this: Printer,\n node: t.OptionalIndexedAccessType,\n) {\n this.print(node.objectType, node);\n if (node.optional) {\n this.token(\"?.\");\n }\n this.token(\"[\");\n this.print(node.indexType, node);\n this.token(\"]\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;;AAEA;;AAidA;;;EAndSA,0B;EAA4BC;;;AAI9B,SAASC,iBAAT,GAA0C;EAC/C,KAAKC,IAAL,CAAU,KAAV;AACD;;AAEM,SAASC,mBAAT,CAELC,IAFK,EAGL;EACA,KAAKC,KAAL,CAAWD,IAAI,CAACE,WAAhB,EAA6BF,IAA7B,EAAmC,IAAnC;EACA,KAAKG,SAAL;EACA,KAAKA,SAAL;AACD;;AAEM,SAASC,qBAAT,GAA8C;EACnD,KAAKN,IAAL,CAAU,SAAV;AACD;;AAEM,SAASO,4BAAT,CAELL,IAFK,EAGL;EACA,KAAKF,IAAL,CAAUE,IAAI,CAACM,KAAL,GAAa,MAAb,GAAsB,OAAhC;AACD;;AAEM,SAASC,yBAAT,GAAkD;EACvD,KAA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,SAASE,kBAAT,CAA2CjI,IAA3C,EAAuE;EAC5E,KAAKG,SAAL;EACA,KAAKF,KAAL,CAAWD,IAAI,CAACkI,UAAhB,EAA4BlI,IAA5B;EACA,KAAKC,KAAL,CAAWD,IAAI,CAACc,cAAhB,EAAgCd,IAAhC;EACA,KAAKG,SAAL;AACD;;AAEM,SAASgI,QAAT,CAAiCnI,IAAjC,EAAmD;EACxD,IAAIA,IAAI,CAACiF,IAAL,KAAc,MAAlB,EAA0B;IACxB,KAAK9E,SAAL;EACD,CAFD,MAEO;IACL,KAAKA,SAAL;EACD;AACF;;AAEM,SAASiI,kBAAT,GAA2C;EAChD,KAAKtI,IAAL,CAAU,MAAV;AACD;;AAEM,SAASuI,iBAAT,CAA0CrI,IAA1C,EAAqE;EAC1E,KAAKC,KAAL,CAAWD,IAAI,CAACsI,UAAhB,EAA4BtI,IAA5B,EAAkC,IAAlC;EACA,KAAKG,SAAL;EACA,KAAKF,KAAL,CAAWD,IAAI,CAACuI,SAAhB,EAA2BvI,IAA3B;EACA,KAAKG,SAAL;AACD;;AAEM,SAASqI,yBAAT,CAELxI,IAFK,EAGL;EACA,KAAKC,KAAL,CAAWD,IAAI,CAACsI,UAAhB,EAA4BtI,IAA5B;;EACA,IAAIA,IAAI,CAAC0E,QAAT,EAAmB;IACjB,KAAKvE,KAAL,CAAW,IAAX;EACD;;EACD,KAAKA,SAAL;EACA,KAAKF,KAAL,CAAWD,IAAI,CAACuI,SAAhB,EAA2BvI,IAA3B;EACA,KAAKG,SAAL;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/index.js b/node_modules/@babel/generator/lib/generators/index.js new file mode 100644 index 0000000..97e73ba --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/index.js @@ -0,0 +1,150 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _templateLiterals = require("./template-literals"); + +Object.keys(_templateLiterals).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _templateLiterals[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _templateLiterals[key]; + } + }); +}); + +var _expressions = require("./expressions"); + +Object.keys(_expressions).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _expressions[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _expressions[key]; + } + }); +}); + +var _statements = require("./statements"); + +Object.keys(_statements).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _statements[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _statements[key]; + } + }); +}); + +var _classes = require("./classes"); + +Object.keys(_classes).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _classes[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _classes[key]; + } + }); +}); + +var _methods = require("./methods"); + +Object.keys(_methods).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _methods[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _methods[key]; + } + }); +}); + +var _modules = require("./modules"); + +Object.keys(_modules).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _modules[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _modules[key]; + } + }); +}); + +var _types = require("./types"); + +Object.keys(_types).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _types[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _types[key]; + } + }); +}); + +var _flow = require("./flow"); + +Object.keys(_flow).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _flow[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _flow[key]; + } + }); +}); + +var _base = require("./base"); + +Object.keys(_base).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _base[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _base[key]; + } + }); +}); + +var _jsx = require("./jsx"); + +Object.keys(_jsx).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _jsx[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _jsx[key]; + } + }); +}); + +var _typescript = require("./typescript"); + +Object.keys(_typescript).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (key in exports && exports[key] === _typescript[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _typescript[key]; + } + }); +}); + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/generator/lib/generators/index.js.map b/node_modules/@babel/generator/lib/generators/index.js.map new file mode 100644 index 0000000..e272e47 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":[],"sources":["../../src/generators/index.ts"],"sourcesContent":["export * from \"./template-literals\";\nexport * from \"./expressions\";\nexport * from \"./statements\";\nexport * from \"./classes\";\nexport * from \"./methods\";\nexport * from \"./modules\";\nexport * from \"./types\";\nexport * from \"./flow\";\nexport * from \"./base\";\nexport * from \"./jsx\";\nexport * from \"./typescript\";\n"],"mappings":";;;;;;AAAA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA;;AACA;;AAAA;EAAA;EAAA;EAAA;IAAA;IAAA;MAAA;IAAA;EAAA;AAAA"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/jsx.js b/node_modules/@babel/generator/lib/generators/jsx.js new file mode 100644 index 0000000..363a145 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/jsx.js @@ -0,0 +1,147 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.JSXAttribute = JSXAttribute; +exports.JSXClosingElement = JSXClosingElement; +exports.JSXClosingFragment = JSXClosingFragment; +exports.JSXElement = JSXElement; +exports.JSXEmptyExpression = JSXEmptyExpression; +exports.JSXExpressionContainer = JSXExpressionContainer; +exports.JSXFragment = JSXFragment; +exports.JSXIdentifier = JSXIdentifier; +exports.JSXMemberExpression = JSXMemberExpression; +exports.JSXNamespacedName = JSXNamespacedName; +exports.JSXOpeningElement = JSXOpeningElement; +exports.JSXOpeningFragment = JSXOpeningFragment; +exports.JSXSpreadAttribute = JSXSpreadAttribute; +exports.JSXSpreadChild = JSXSpreadChild; +exports.JSXText = JSXText; + +function JSXAttribute(node) { + this.print(node.name, node); + + if (node.value) { + this.tokenChar(61); + this.print(node.value, node); + } +} + +function JSXIdentifier(node) { + this.word(node.name); +} + +function JSXNamespacedName(node) { + this.print(node.namespace, node); + this.tokenChar(58); + this.print(node.name, node); +} + +function JSXMemberExpression(node) { + this.print(node.object, node); + this.tokenChar(46); + this.print(node.property, node); +} + +function JSXSpreadAttribute(node) { + this.tokenChar(123); + this.token("..."); + this.print(node.argument, node); + this.tokenChar(125); +} + +function JSXExpressionContainer(node) { + this.tokenChar(123); + this.print(node.expression, node); + this.tokenChar(125); +} + +function JSXSpreadChild(node) { + this.tokenChar(123); + this.token("..."); + this.print(node.expression, node); + this.tokenChar(125); +} + +function JSXText(node) { + const raw = this.getPossibleRaw(node); + + if (raw !== undefined) { + this.token(raw, true); + } else { + this.token(node.value, true); + } +} + +function JSXElement(node) { + const open = node.openingElement; + this.print(open, node); + if (open.selfClosing) return; + this.indent(); + + for (const child of node.children) { + this.print(child, node); + } + + this.dedent(); + this.print(node.closingElement, node); +} + +function spaceSeparator() { + this.space(); +} + +function JSXOpeningElement(node) { + this.tokenChar(60); + this.print(node.name, node); + this.print(node.typeParameters, node); + + if (node.attributes.length > 0) { + this.space(); + this.printJoin(node.attributes, node, { + separator: spaceSeparator + }); + } + + if (node.selfClosing) { + this.space(); + this.token("/>"); + } else { + this.tokenChar(62); + } +} + +function JSXClosingElement(node) { + this.token(" 0) {\n this.space();\n this.printJoin(node.attributes, node, { separator: spaceSeparator });\n }\n if (node.selfClosing) {\n this.space();\n this.token(\"/>\");\n } else {\n this.token(\">\");\n }\n}\n\nexport function JSXClosingElement(this: Printer, node: t.JSXClosingElement) {\n this.token(\"\");\n}\n\nexport function JSXEmptyExpression(this: Printer, node: t.JSXEmptyExpression) {\n this.printInnerComments(node);\n}\n\nexport function JSXFragment(this: Printer, node: t.JSXFragment) {\n this.print(node.openingFragment, node);\n\n this.indent();\n for (const child of node.children) {\n this.print(child, node);\n }\n this.dedent();\n\n this.print(node.closingFragment, node);\n}\n\nexport function JSXOpeningFragment(this: Printer) {\n this.token(\"<\");\n this.token(\">\");\n}\n\nexport function JSXClosingFragment(this: Printer) {\n this.token(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAGO,SAASA,YAAT,CAAqCC,IAArC,EAA2D;EAChE,KAAKC,KAAL,CAAWD,IAAI,CAACE,IAAhB,EAAsBF,IAAtB;;EACA,IAAIA,IAAI,CAACG,KAAT,EAAgB;IACd,KAAKC,SAAL;IACA,KAAKH,KAAL,CAAWD,IAAI,CAACG,KAA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AuE;EAC5E,KAAKwC,kBAAL,CAAwBxC,IAAxB;AACD;;AAEM,SAASyC,WAAT,CAAoCzC,IAApC,EAAyD;EAC9D,KAAKC,KAAL,CAAWD,IAAI,CAAC0C,eAAhB,EAAiC1C,IAAjC;EAEA,KAAKyB,MAAL;;EACA,KAAK,MAAMC,KAAX,IAAoB1B,IAAI,CAAC2B,QAAzB,EAAmC;IACjC,KAAK1B,KAAL,CAAWyB,KAAX,EAAkB1B,IAAlB;EACD;;EACD,KAAK4B,MAAL;EAEA,KAAK3B,KAAL,CAAWD,IAAI,CAAC2C,eAAhB,EAAiC3C,IAAjC;AACD;;AAEM,SAAS4C,kBAAT,GAA2C;EAChD,KAAKxC,SAAL;EACA,KAAKA,SAAL;AACD;;AAEM,SAASyC,kBAAT,GAA2C;EAChD,KAAKzC,KAAL,CAAW,IAAX;EACA,KAAKA,SAAL;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/methods.js b/node_modules/@babel/generator/lib/generators/methods.js new file mode 100644 index 0000000..1018e21 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/methods.js @@ -0,0 +1,158 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ArrowFunctionExpression = ArrowFunctionExpression; +exports.FunctionDeclaration = exports.FunctionExpression = FunctionExpression; +exports._functionHead = _functionHead; +exports._methodHead = _methodHead; +exports._param = _param; +exports._parameters = _parameters; +exports._params = _params; +exports._predicate = _predicate; + +var _t = require("@babel/types"); + +const { + isIdentifier +} = _t; + +function _params(node) { + this.print(node.typeParameters, node); + this.tokenChar(40); + + this._parameters(node.params, node); + + this.tokenChar(41); + this.print(node.returnType, node, node.type === "ArrowFunctionExpression"); +} + +function _parameters(parameters, parent) { + for (let i = 0; i < parameters.length; i++) { + this._param(parameters[i], parent); + + if (i < parameters.length - 1) { + this.tokenChar(44); + this.space(); + } + } +} + +function _param(parameter, parent) { + this.printJoin(parameter.decorators, parameter); + this.print(parameter, parent); + + if (parameter.optional) { + this.tokenChar(63); + } + + this.print(parameter.typeAnnotation, parameter); +} + +function _methodHead(node) { + const kind = node.kind; + const key = node.key; + + if (kind === "get" || kind === "set") { + this.word(kind); + this.space(); + } + + if (node.async) { + this._catchUp("start", key.loc); + + this.word("async"); + this.space(); + } + + if (kind === "method" || kind === "init") { + if (node.generator) { + this.tokenChar(42); + } + } + + if (node.computed) { + this.tokenChar(91); + this.print(key, node); + this.tokenChar(93); + } else { + this.print(key, node); + } + + if (node.optional) { + this.tokenChar(63); + } + + this._params(node); +} + +function _predicate(node) { + if (node.predicate) { + if (!node.returnType) { + this.tokenChar(58); + } + + this.space(); + this.print(node.predicate, node); + } +} + +function _functionHead(node) { + if (node.async) { + this.word("async"); + this.space(); + } + + this.word("function"); + if (node.generator) this.tokenChar(42); + this.printInnerComments(node); + this.space(); + + if (node.id) { + this.print(node.id, node); + } + + this._params(node); + + if (node.type !== "TSDeclareFunction") { + this._predicate(node); + } +} + +function FunctionExpression(node) { + this._functionHead(node); + + this.space(); + this.print(node.body, node); +} + +function ArrowFunctionExpression(node) { + if (node.async) { + this.word("async"); + this.space(); + } + + const firstParam = node.params[0]; + + if (!this.format.retainLines && !this.format.auxiliaryCommentBefore && !this.format.auxiliaryCommentAfter && node.params.length === 1 && isIdentifier(firstParam) && !hasTypesOrComments(node, firstParam)) { + this.print(firstParam, node); + } else { + this._params(node); + } + + this._predicate(node); + + this.space(); + this.token("=>"); + this.space(); + this.print(node.body, node); +} + +function hasTypesOrComments(node, param) { + var _param$leadingComment, _param$trailingCommen; + + return !!(node.typeParameters || node.returnType || node.predicate || param.typeAnnotation || param.optional || (_param$leadingComment = param.leadingComments) != null && _param$leadingComment.length || (_param$trailingCommen = param.trailingComments) != null && _param$trailingCommen.length); +} + +//# sourceMappingURL=methods.js.map diff --git a/node_modules/@babel/generator/lib/generators/methods.js.map b/node_modules/@babel/generator/lib/generators/methods.js.map new file mode 100644 index 0000000..b058ed7 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/methods.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isIdentifier","_params","node","print","typeParameters","token","_parameters","params","returnType","type","parameters","parent","i","length","_param","space","parameter","printJoin","decorators","optional","typeAnnotation","_methodHead","kind","key","word","async","_catchUp","loc","generator","computed","_predicate","predicate","_functionHead","printInnerComments","id","FunctionExpression","body","ArrowFunctionExpression","firstParam","format","retainLines","auxiliaryCommentBefore","auxiliaryCommentAfter","hasTypesOrComments","param","leadingComments","trailingComments"],"sources":["../../src/generators/methods.ts"],"sourcesContent":["import type Printer from \"../printer\";\nimport { isIdentifier } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\n\nexport function _params(\n this: Printer,\n node: t.Function | t.TSDeclareMethod | t.TSDeclareFunction,\n) {\n this.print(node.typeParameters, node);\n this.token(\"(\");\n this._parameters(node.params, node);\n this.token(\")\");\n\n this.print(node.returnType, node, node.type === \"ArrowFunctionExpression\");\n}\n\nexport function _parameters(\n this: Printer,\n parameters: t.Function[\"params\"],\n parent:\n | t.Function\n | t.TSIndexSignature\n | t.TSDeclareMethod\n | t.TSDeclareFunction\n | t.TSFunctionType\n | t.TSConstructorType,\n) {\n for (let i = 0; i < parameters.length; i++) {\n this._param(parameters[i], parent);\n\n if (i < parameters.length - 1) {\n this.token(\",\");\n this.space();\n }\n }\n}\n\nexport function _param(\n this: Printer,\n parameter: t.Identifier | t.RestElement | t.Pattern | t.TSParameterProperty,\n parent?:\n | t.Function\n | t.TSIndexSignature\n | t.TSDeclareMethod\n | t.TSDeclareFunction\n | t.TSFunctionType\n | t.TSConstructorType,\n) {\n this.printJoin(parameter.decorators, parameter);\n this.print(parameter, parent);\n if (\n // @ts-expect-error optional is not in TSParameterProperty\n parameter.optional\n ) {\n this.token(\"?\"); // TS / flow\n }\n\n this.print(\n // @ts-expect-error typeAnnotation is not in TSParameterProperty\n parameter.typeAnnotation,\n parameter,\n ); // TS / flow\n}\n\nexport function _methodHead(this: Printer, node: t.Method | t.TSDeclareMethod) {\n const kind = node.kind;\n const key = node.key;\n\n if (kind === \"get\" || kind === \"set\") {\n this.word(kind);\n this.space();\n }\n\n if (node.async) {\n // ensure `async` is in the same line with property name\n this._catchUp(\"start\", key.loc);\n this.word(\"async\");\n this.space();\n }\n\n if (\n kind === \"method\" ||\n // @ts-expect-error Fixme: kind: \"init\" is not defined\n kind === \"init\"\n ) {\n if (node.generator) {\n this.token(\"*\");\n }\n }\n\n if (node.computed) {\n this.token(\"[\");\n this.print(key, node);\n this.token(\"]\");\n } else {\n this.print(key, node);\n }\n\n if (\n // @ts-expect-error optional is not in ObjectMethod\n node.optional\n ) {\n // TS\n this.token(\"?\");\n }\n\n this._params(node);\n}\n\nexport function _predicate(\n this: Printer,\n node:\n | t.FunctionDeclaration\n | t.FunctionExpression\n | t.ArrowFunctionExpression,\n) {\n if (node.predicate) {\n if (!node.returnType) {\n this.token(\":\");\n }\n this.space();\n this.print(node.predicate, node);\n }\n}\n\nexport function _functionHead(\n this: Printer,\n node: t.FunctionDeclaration | t.FunctionExpression | t.TSDeclareFunction,\n) {\n if (node.async) {\n this.word(\"async\");\n this.space();\n }\n this.word(\"function\");\n if (node.generator) this.token(\"*\");\n this.printInnerComments(node);\n\n this.space();\n if (node.id) {\n this.print(node.id, node);\n }\n\n this._params(node);\n if (node.type !== \"TSDeclareFunction\") {\n this._predicate(node);\n }\n}\n\nexport function FunctionExpression(this: Printer, node: t.FunctionExpression) {\n this._functionHead(node);\n this.space();\n this.print(node.body, node);\n}\n\nexport { FunctionExpression as FunctionDeclaration };\n\nexport function ArrowFunctionExpression(\n this: Printer,\n node: t.ArrowFunctionExpression,\n) {\n if (node.async) {\n this.word(\"async\");\n this.space();\n }\n\n const firstParam = node.params[0];\n\n // Try to avoid printing parens in simple cases, but only if we're pretty\n // sure that they aren't needed by type annotations or potential newlines.\n if (\n !this.format.retainLines &&\n // Auxiliary comments can introduce unexpected newlines\n !this.format.auxiliaryCommentBefore &&\n !this.format.auxiliaryCommentAfter &&\n node.params.length === 1 &&\n isIdentifier(firstParam) &&\n !hasTypesOrComments(node, firstParam)\n ) {\n this.print(firstParam, node);\n } else {\n this._params(node);\n }\n\n this._predicate(node);\n\n this.space();\n this.token(\"=>\");\n this.space();\n\n this.print(node.body, node);\n}\n\nfunction hasTypesOrComments(\n node: t.ArrowFunctionExpression,\n param: t.Identifier,\n): boolean {\n return !!(\n node.typeParameters ||\n node.returnType ||\n node.predicate ||\n param.typeAnnotation ||\n param.optional ||\n param.leadingComments?.length ||\n param.trailingComments?.length\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AACA;;;EAASA;;;AAGF,SAASC,OAAT,CAELC,IAFK,EAGL;EACA,KAAKC,KAAL,CAAWD,IAAI,CAACE,cAAhB,EAAgCF,IAAhC;EACA,KAAKG,SAAL;;EACA,KAAKC,WAAL,CAAiBJ,IAAI,CAACK,MAAtB,EAA8BL,IAA9B;;EACA,KAAKG,SAAL;EAEA,KAAKF,KAAL,CAAWD,IAAI,CAACM,UAAhB,EAA4BN,IAA5B,EAAkCA,IAAI,CAACO,IAAL,KAAc,yBAAhD;AACD;;AAEM,SAASH,WAAT,CAELI,UAFK,EAGLC,MAHK,EAUL;EACA,KAAK,IAAIC,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGF,UAAU,CAACG,MAA/B,EAAuCD,CAAC,EAAxC,EAA4C;IAC1C,KAAKE,MAAL,CAAYJ,UAAU,CAACE,CAAD,CAAtB,EAA2BD,MAA3B;;IAEA,IAAIC,CAAC,GAAGF,UAAU,CAACG,MAAX,GAAoB,CAA5B,EAA+B;MAC7B,KAAKR,SAAL;MACA,KAAKU,KAAL;IACD;EACF;AACF;;AAEM,SAASD,MAAT,CAELE,SAFK,EAGLL,MAHK,EAUL;EACA,KAAKM,SAAL,CAAeD,SAAS,CAACE,UAAzB,EAAqCF,SAArC;EACA,KAAKb,KAAL,CAAWa,SAAX,EAAsBL,MAAtB;;EACA,IAEEK,SAAS,CAACG,QAFZ,EAGE;IACA,KAAKd,SAAL;E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EAEA,KAAKa,KAAL;EACA,KAAKV,KAAL,CAAW,IAAX;EACA,KAAKU,KAAL;EAEA,KAAKZ,KAAL,CAAWD,IAAI,CAACkC,IAAhB,EAAsBlC,IAAtB;AACD;;AAED,SAASyC,kBAAT,CACEzC,IADF,EAEE0C,KAFF,EAGW;EAAA;;EACT,OAAO,CAAC,EACN1C,IAAI,CAACE,cAAL,IACAF,IAAI,CAACM,UADL,IAEAN,IAAI,CAAC6B,SAFL,IAGAa,KAAK,CAACxB,cAHN,IAIAwB,KAAK,CAACzB,QAJN,6BAKAyB,KAAK,CAACC,eALN,aAKA,sBAAuBhC,MALvB,6BAMA+B,KAAK,CAACE,gBANN,aAMA,sBAAwBjC,MAPlB,CAAR;AASD"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/modules.js b/node_modules/@babel/generator/lib/generators/modules.js new file mode 100644 index 0000000..cd3ba11 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/modules.js @@ -0,0 +1,247 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ExportAllDeclaration = ExportAllDeclaration; +exports.ExportDefaultDeclaration = ExportDefaultDeclaration; +exports.ExportDefaultSpecifier = ExportDefaultSpecifier; +exports.ExportNamedDeclaration = ExportNamedDeclaration; +exports.ExportNamespaceSpecifier = ExportNamespaceSpecifier; +exports.ExportSpecifier = ExportSpecifier; +exports.ImportAttribute = ImportAttribute; +exports.ImportDeclaration = ImportDeclaration; +exports.ImportDefaultSpecifier = ImportDefaultSpecifier; +exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; +exports.ImportSpecifier = ImportSpecifier; + +var _t = require("@babel/types"); + +const { + isClassDeclaration, + isExportDefaultSpecifier, + isExportNamespaceSpecifier, + isImportDefaultSpecifier, + isImportNamespaceSpecifier, + isStatement +} = _t; + +function ImportSpecifier(node) { + if (node.importKind === "type" || node.importKind === "typeof") { + this.word(node.importKind); + this.space(); + } + + this.print(node.imported, node); + + if (node.local && node.local.name !== node.imported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.local, node); + } +} + +function ImportDefaultSpecifier(node) { + this.print(node.local, node); +} + +function ExportDefaultSpecifier(node) { + this.print(node.exported, node); +} + +function ExportSpecifier(node) { + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + + this.print(node.local, node); + + if (node.exported && node.local.name !== node.exported.name) { + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); + } +} + +function ExportNamespaceSpecifier(node) { + this.tokenChar(42); + this.space(); + this.word("as"); + this.space(); + this.print(node.exported, node); +} + +function ExportAllDeclaration(node) { + this.word("export"); + this.space(); + + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + + this.tokenChar(42); + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + this.printAssertions(node); + this.semicolon(); +} + +function ExportNamedDeclaration(node) { + { + if (this.format.decoratorsBeforeExport && isClassDeclaration(node.declaration)) { + this.printJoin(node.declaration.decorators, node); + } + } + this.word("export"); + this.space(); + + if (node.declaration) { + const declar = node.declaration; + this.print(declar, node); + if (!isStatement(declar)) this.semicolon(); + } else { + if (node.exportKind === "type") { + this.word("type"); + this.space(); + } + + const specifiers = node.specifiers.slice(0); + let hasSpecial = false; + + for (;;) { + const first = specifiers[0]; + + if (isExportDefaultSpecifier(first) || isExportNamespaceSpecifier(first)) { + hasSpecial = true; + this.print(specifiers.shift(), node); + + if (specifiers.length) { + this.tokenChar(44); + this.space(); + } + } else { + break; + } + } + + if (specifiers.length || !specifiers.length && !hasSpecial) { + this.tokenChar(123); + + if (specifiers.length) { + this.space(); + this.printList(specifiers, node); + this.space(); + } + + this.tokenChar(125); + } + + if (node.source) { + this.space(); + this.word("from"); + this.space(); + this.print(node.source, node); + this.printAssertions(node); + } + + this.semicolon(); + } +} + +function ExportDefaultDeclaration(node) { + { + if (this.format.decoratorsBeforeExport && isClassDeclaration(node.declaration)) { + this.printJoin(node.declaration.decorators, node); + } + } + this.word("export"); + this.space(); + this.word("default"); + this.space(); + const declar = node.declaration; + this.print(declar, node); + if (!isStatement(declar)) this.semicolon(); +} + +function ImportDeclaration(node) { + this.word("import"); + this.space(); + const isTypeKind = node.importKind === "type" || node.importKind === "typeof"; + + if (isTypeKind) { + this.word(node.importKind); + this.space(); + } + + const specifiers = node.specifiers.slice(0); + const hasSpecifiers = !!specifiers.length; + + while (hasSpecifiers) { + const first = specifiers[0]; + + if (isImportDefaultSpecifier(first) || isImportNamespaceSpecifier(first)) { + this.print(specifiers.shift(), node); + + if (specifiers.length) { + this.tokenChar(44); + this.space(); + } + } else { + break; + } + } + + if (specifiers.length) { + this.tokenChar(123); + this.space(); + this.printList(specifiers, node); + this.space(); + this.tokenChar(125); + } else if (isTypeKind && !hasSpecifiers) { + this.tokenChar(123); + this.tokenChar(125); + } + + if (hasSpecifiers || isTypeKind) { + this.space(); + this.word("from"); + this.space(); + } + + this.print(node.source, node); + this.printAssertions(node); + { + var _node$attributes; + + if ((_node$attributes = node.attributes) != null && _node$attributes.length) { + this.space(); + this.word("with"); + this.space(); + this.printList(node.attributes, node); + } + } + this.semicolon(); +} + +function ImportAttribute(node) { + this.print(node.key); + this.tokenChar(58); + this.space(); + this.print(node.value); +} + +function ImportNamespaceSpecifier(node) { + this.tokenChar(42); + this.space(); + this.word("as"); + this.space(); + this.print(node.local, node); +} + +//# sourceMappingURL=modules.js.map diff --git a/node_modules/@babel/generator/lib/generators/modules.js.map b/node_modules/@babel/generator/lib/generators/modules.js.map new file mode 100644 index 0000000..2ddae7c --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/modules.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isClassDeclaration","isExportDefaultSpecifier","isExportNamespaceSpecifier","isImportDefaultSpecifier","isImportNamespaceSpecifier","isStatement","ImportSpecifier","node","importKind","word","space","print","imported","local","name","ImportDefaultSpecifier","ExportDefaultSpecifier","exported","ExportSpecifier","exportKind","ExportNamespaceSpecifier","token","ExportAllDeclaration","source","printAssertions","semicolon","ExportNamedDeclaration","format","decoratorsBeforeExport","declaration","printJoin","decorators","declar","specifiers","slice","hasSpecial","first","shift","length","printList","ExportDefaultDeclaration","ImportDeclaration","isTypeKind","hasSpecifiers","attributes","ImportAttribute","key","value","ImportNamespaceSpecifier"],"sources":["../../src/generators/modules.ts"],"sourcesContent":["import type Printer from \"../printer\";\nimport {\n isClassDeclaration,\n isExportDefaultSpecifier,\n isExportNamespaceSpecifier,\n isImportDefaultSpecifier,\n isImportNamespaceSpecifier,\n isStatement,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\n\nexport function ImportSpecifier(this: Printer, node: t.ImportSpecifier) {\n if (node.importKind === \"type\" || node.importKind === \"typeof\") {\n this.word(node.importKind);\n this.space();\n }\n\n this.print(node.imported, node);\n // @ts-expect-error todo(flow-ts) maybe check node type instead of relying on name to be undefined on t.StringLiteral\n if (node.local && node.local.name !== node.imported.name) {\n this.space();\n this.word(\"as\");\n this.space();\n this.print(node.local, node);\n }\n}\n\nexport function ImportDefaultSpecifier(\n this: Printer,\n node: t.ImportDefaultSpecifier,\n) {\n this.print(node.local, node);\n}\n\nexport function ExportDefaultSpecifier(\n this: Printer,\n node: t.ExportDefaultSpecifier,\n) {\n this.print(node.exported, node);\n}\n\nexport function ExportSpecifier(this: Printer, node: t.ExportSpecifier) {\n if (node.exportKind === \"type\") {\n this.word(\"type\");\n this.space();\n }\n\n this.print(node.local, node);\n // @ts-expect-error todo(flow-ts) maybe check node type instead of relying on name to be undefined on t.StringLiteral\n if (node.exported && node.local.name !== node.exported.name) {\n this.space();\n this.word(\"as\");\n this.space();\n this.print(node.exported, node);\n }\n}\n\nexport function ExportNamespaceSpecifier(\n this: Printer,\n node: t.ExportNamespaceSpecifier,\n) {\n this.token(\"*\");\n this.space();\n this.word(\"as\");\n this.space();\n this.print(node.exported, node);\n}\n\nexport function ExportAllDeclaration(\n this: Printer,\n node: t.ExportAllDeclaration | t.DeclareExportAllDeclaration,\n) {\n this.word(\"export\");\n this.space();\n if (node.exportKind === \"type\") {\n this.word(\"type\");\n this.space();\n }\n this.token(\"*\");\n this.space();\n this.word(\"from\");\n this.space();\n this.print(node.source, node);\n // @ts-expect-error Fixme: assertions is not defined in DeclareExportAllDeclaration\n this.printAssertions(node);\n this.semicolon();\n}\n\nexport function ExportNamedDeclaration(\n this: Printer,\n node: t.ExportNamedDeclaration,\n) {\n if (!process.env.BABEL_8_BREAKING) {\n if (\n this.format.decoratorsBeforeExport &&\n isClassDeclaration(node.declaration)\n ) {\n this.printJoin(node.declaration.decorators, node);\n }\n }\n\n this.word(\"export\");\n this.space();\n if (node.declaration) {\n const declar = node.declaration;\n this.print(declar, node);\n if (!isStatement(declar)) this.semicolon();\n } else {\n if (node.exportKind === \"type\") {\n this.word(\"type\");\n this.space();\n }\n\n const specifiers = node.specifiers.slice(0);\n\n // print \"special\" specifiers first\n let hasSpecial = false;\n for (;;) {\n const first = specifiers[0];\n if (\n isExportDefaultSpecifier(first) ||\n isExportNamespaceSpecifier(first)\n ) {\n hasSpecial = true;\n this.print(specifiers.shift(), node);\n if (specifiers.length) {\n this.token(\",\");\n this.space();\n }\n } else {\n break;\n }\n }\n\n if (specifiers.length || (!specifiers.length && !hasSpecial)) {\n this.token(\"{\");\n if (specifiers.length) {\n this.space();\n this.printList(specifiers, node);\n this.space();\n }\n this.token(\"}\");\n }\n\n if (node.source) {\n this.space();\n this.word(\"from\");\n this.space();\n this.print(node.source, node);\n this.printAssertions(node);\n }\n\n this.semicolon();\n }\n}\n\nexport function ExportDefaultDeclaration(\n this: Printer,\n node: t.ExportDefaultDeclaration,\n) {\n if (!process.env.BABEL_8_BREAKING) {\n if (\n this.format.decoratorsBeforeExport &&\n isClassDeclaration(node.declaration)\n ) {\n this.printJoin(node.declaration.decorators, node);\n }\n }\n\n this.word(\"export\");\n this.space();\n this.word(\"default\");\n this.space();\n const declar = node.declaration;\n this.print(declar, node);\n if (!isStatement(declar)) this.semicolon();\n}\n\nexport function ImportDeclaration(this: Printer, node: t.ImportDeclaration) {\n this.word(\"import\");\n this.space();\n\n const isTypeKind = node.importKind === \"type\" || node.importKind === \"typeof\";\n if (isTypeKind) {\n this.word(node.importKind);\n this.space();\n }\n\n const specifiers = node.specifiers.slice(0);\n const hasSpecifiers = !!specifiers.length;\n // print \"special\" specifiers first. The loop condition is constant,\n // but there is a \"break\" in the body.\n while (hasSpecifiers) {\n const first = specifiers[0];\n if (isImportDefaultSpecifier(first) || isImportNamespaceSpecifier(first)) {\n this.print(specifiers.shift(), node);\n if (specifiers.length) {\n this.token(\",\");\n this.space();\n }\n } else {\n break;\n }\n }\n\n if (specifiers.length) {\n this.token(\"{\");\n this.space();\n this.printList(specifiers, node);\n this.space();\n this.token(\"}\");\n } else if (isTypeKind && !hasSpecifiers) {\n this.token(\"{\");\n this.token(\"}\");\n }\n\n if (hasSpecifiers || isTypeKind) {\n this.space();\n this.word(\"from\");\n this.space();\n }\n\n this.print(node.source, node);\n\n this.printAssertions(node);\n if (!process.env.BABEL_8_BREAKING) {\n // @ts-ignore(Babel 7 vs Babel 8) Babel 7 supports module attributes\n if (node.attributes?.length) {\n this.space();\n this.word(\"with\");\n this.space();\n // @ts-ignore(Babel 7 vs Babel 8) Babel 7 supports module attributes\n this.printList(node.attributes, node);\n }\n }\n\n this.semicolon();\n}\n\nexport function ImportAttribute(this: Printer, node: t.ImportAttribute) {\n this.print(node.key);\n this.token(\":\");\n this.space();\n this.print(node.value);\n}\n\nexport function ImportNamespaceSpecifier(\n this: Printer,\n node: t.ImportNamespaceSpecifier,\n) {\n this.token(\"*\");\n this.space();\n this.word(\"as\");\n this.space();\n this.print(node.local, node);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AACA;;;EACEA,kB;EACAC,wB;EACAC,0B;EACAC,wB;EACAC,0B;EACAC;;;AAIK,SAASC,eAAT,CAAwCC,IAAxC,EAAiE;EACtE,IAAIA,IAAI,CAACC,UAAL,KAAoB,MAApB,IAA8BD,IAAI,CAACC,UAAL,KAAoB,QAAtD,EAAgE;IAC9D,KAA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,CAACgB,MAAhB,EAAwBhB,IAAxB;EAEA,KAAKiB,eAAL,CAAqBjB,IAArB;EACmC;IAAA;;IAEjC,wBAAIA,IAAI,CAACqC,UAAT,aAAI,iBAAiBN,MAArB,EAA6B;MAC3B,KAAK5B,KAAL;MACA,KAAKD,IAAL,CAAU,MAAV;MACA,KAAKC,KAAL;MAEA,KAAK6B,SAAL,CAAehC,IAAI,CAACqC,UAApB,EAAgCrC,IAAhC;IACD;EACF;EAED,KAAKkB,SAAL;AACD;;AAEM,SAASoB,eAAT,CAAwCtC,IAAxC,EAAiE;EACtE,KAAKI,KAAL,CAAWJ,IAAI,CAACuC,GAAhB;EACA,KAAKzB,SAAL;EACA,KAAKX,KAAL;EACA,KAAKC,KAAL,CAAWJ,IAAI,CAACwC,KAAhB;AACD;;AAEM,SAASC,wBAAT,CAELzC,IAFK,EAGL;EACA,KAAKc,SAAL;EACA,KAAKX,KAAL;EACA,KAAKD,IAAL,CAAU,IAAV;EACA,KAAKC,KAAL;EACA,KAAKC,KAAL,CAAWJ,IAAI,CAACM,KAAhB,EAAuBN,IAAvB;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/statements.js b/node_modules/@babel/generator/lib/generators/statements.js new file mode 100644 index 0000000..b1b38a3 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/statements.js @@ -0,0 +1,322 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BreakStatement = BreakStatement; +exports.CatchClause = CatchClause; +exports.ContinueStatement = ContinueStatement; +exports.DebuggerStatement = DebuggerStatement; +exports.DoWhileStatement = DoWhileStatement; +exports.ForOfStatement = exports.ForInStatement = void 0; +exports.ForStatement = ForStatement; +exports.IfStatement = IfStatement; +exports.LabeledStatement = LabeledStatement; +exports.ReturnStatement = ReturnStatement; +exports.SwitchCase = SwitchCase; +exports.SwitchStatement = SwitchStatement; +exports.ThrowStatement = ThrowStatement; +exports.TryStatement = TryStatement; +exports.VariableDeclaration = VariableDeclaration; +exports.VariableDeclarator = VariableDeclarator; +exports.WhileStatement = WhileStatement; +exports.WithStatement = WithStatement; + +var _t = require("@babel/types"); + +const { + isFor, + isForStatement, + isIfStatement, + isStatement +} = _t; + +function WithStatement(node) { + this.word("with"); + this.space(); + this.tokenChar(40); + this.print(node.object, node); + this.tokenChar(41); + this.printBlock(node); +} + +function IfStatement(node) { + this.word("if"); + this.space(); + this.tokenChar(40); + this.print(node.test, node); + this.tokenChar(41); + this.space(); + const needsBlock = node.alternate && isIfStatement(getLastStatement(node.consequent)); + + if (needsBlock) { + this.tokenChar(123); + this.newline(); + this.indent(); + } + + this.printAndIndentOnComments(node.consequent, node); + + if (needsBlock) { + this.dedent(); + this.newline(); + this.tokenChar(125); + } + + if (node.alternate) { + if (this.endsWith(125)) this.space(); + this.word("else"); + this.space(); + this.printAndIndentOnComments(node.alternate, node); + } +} + +function getLastStatement(statement) { + const { + body + } = statement; + + if (isStatement(body) === false) { + return statement; + } + + return getLastStatement(body); +} + +function ForStatement(node) { + this.word("for"); + this.space(); + this.tokenChar(40); + this.inForStatementInitCounter++; + this.print(node.init, node); + this.inForStatementInitCounter--; + this.tokenChar(59); + + if (node.test) { + this.space(); + this.print(node.test, node); + } + + this.tokenChar(59); + + if (node.update) { + this.space(); + this.print(node.update, node); + } + + this.tokenChar(41); + this.printBlock(node); +} + +function WhileStatement(node) { + this.word("while"); + this.space(); + this.tokenChar(40); + this.print(node.test, node); + this.tokenChar(41); + this.printBlock(node); +} + +function ForXStatement(node) { + this.word("for"); + this.space(); + const isForOf = node.type === "ForOfStatement"; + + if (isForOf && node.await) { + this.word("await"); + this.space(); + } + + this.tokenChar(40); + this.print(node.left, node); + this.space(); + this.word(isForOf ? "of" : "in"); + this.space(); + this.print(node.right, node); + this.tokenChar(41); + this.printBlock(node); +} + +const ForInStatement = ForXStatement; +exports.ForInStatement = ForInStatement; +const ForOfStatement = ForXStatement; +exports.ForOfStatement = ForOfStatement; + +function DoWhileStatement(node) { + this.word("do"); + this.space(); + this.print(node.body, node); + this.space(); + this.word("while"); + this.space(); + this.tokenChar(40); + this.print(node.test, node); + this.tokenChar(41); + this.semicolon(); +} + +function printStatementAfterKeyword(printer, node, parent, isLabel) { + if (node) { + printer.space(); + printer.printTerminatorless(node, parent, isLabel); + } + + printer.semicolon(); +} + +function BreakStatement(node) { + this.word("break"); + printStatementAfterKeyword(this, node.label, node, true); +} + +function ContinueStatement(node) { + this.word("continue"); + printStatementAfterKeyword(this, node.label, node, true); +} + +function ReturnStatement(node) { + this.word("return"); + printStatementAfterKeyword(this, node.argument, node, false); +} + +function ThrowStatement(node) { + this.word("throw"); + printStatementAfterKeyword(this, node.argument, node, false); +} + +function LabeledStatement(node) { + this.print(node.label, node); + this.tokenChar(58); + this.space(); + this.print(node.body, node); +} + +function TryStatement(node) { + this.word("try"); + this.space(); + this.print(node.block, node); + this.space(); + + if (node.handlers) { + this.print(node.handlers[0], node); + } else { + this.print(node.handler, node); + } + + if (node.finalizer) { + this.space(); + this.word("finally"); + this.space(); + this.print(node.finalizer, node); + } +} + +function CatchClause(node) { + this.word("catch"); + this.space(); + + if (node.param) { + this.tokenChar(40); + this.print(node.param, node); + this.print(node.param.typeAnnotation, node); + this.tokenChar(41); + this.space(); + } + + this.print(node.body, node); +} + +function SwitchStatement(node) { + this.word("switch"); + this.space(); + this.tokenChar(40); + this.print(node.discriminant, node); + this.tokenChar(41); + this.space(); + this.tokenChar(123); + this.printSequence(node.cases, node, { + indent: true, + + addNewlines(leading, cas) { + if (!leading && node.cases[node.cases.length - 1] === cas) return -1; + } + + }); + this.tokenChar(125); +} + +function SwitchCase(node) { + if (node.test) { + this.word("case"); + this.space(); + this.print(node.test, node); + this.tokenChar(58); + } else { + this.word("default"); + this.tokenChar(58); + } + + if (node.consequent.length) { + this.newline(); + this.printSequence(node.consequent, node, { + indent: true + }); + } +} + +function DebuggerStatement() { + this.word("debugger"); + this.semicolon(); +} + +function VariableDeclaration(node, parent) { + if (node.declare) { + this.word("declare"); + this.space(); + } + + this.word(node.kind); + this.space(); + let hasInits = false; + + if (!isFor(parent)) { + for (const declar of node.declarations) { + if (declar.init) { + hasInits = true; + } + } + } + + this.printList(node.declarations, node, { + separator: hasInits ? function () { + this.tokenChar(44); + this.newline(); + } : undefined, + indent: node.declarations.length > 1 ? true : false + }); + + if (isFor(parent)) { + if (isForStatement(parent)) { + if (parent.init === node) return; + } else { + if (parent.left === node) return; + } + } + + this.semicolon(); +} + +function VariableDeclarator(node) { + this.print(node.id, node); + if (node.definite) this.tokenChar(33); + this.print(node.id.typeAnnotation, node); + + if (node.init) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.init, node); + } +} + +//# sourceMappingURL=statements.js.map diff --git a/node_modules/@babel/generator/lib/generators/statements.js.map b/node_modules/@babel/generator/lib/generators/statements.js.map new file mode 100644 index 0000000..533c19f --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/statements.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isFor","isForStatement","isIfStatement","isStatement","WithStatement","node","word","space","token","print","object","printBlock","IfStatement","test","needsBlock","alternate","getLastStatement","consequent","newline","indent","printAndIndentOnComments","dedent","endsWith","statement","body","ForStatement","inForStatementInitCounter","init","update","WhileStatement","ForXStatement","isForOf","type","await","left","right","ForInStatement","ForOfStatement","DoWhileStatement","semicolon","printStatementAfterKeyword","printer","parent","isLabel","printTerminatorless","BreakStatement","label","ContinueStatement","ReturnStatement","argument","ThrowStatement","LabeledStatement","TryStatement","block","handlers","handler","finalizer","CatchClause","param","typeAnnotation","SwitchStatement","discriminant","printSequence","cases","addNewlines","leading","cas","length","SwitchCase","DebuggerStatement","VariableDeclaration","declare","kind","hasInits","declar","declarations","printList","separator","undefined","VariableDeclarator","id","definite"],"sources":["../../src/generators/statements.ts"],"sourcesContent":["import type Printer from \"../printer\";\nimport {\n isFor,\n isForStatement,\n isIfStatement,\n isStatement,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport * as charCodes from \"charcodes\";\n\nexport function WithStatement(this: Printer, node: t.WithStatement) {\n this.word(\"with\");\n this.space();\n this.token(\"(\");\n this.print(node.object, node);\n this.token(\")\");\n this.printBlock(node);\n}\n\nexport function IfStatement(this: Printer, node: t.IfStatement) {\n this.word(\"if\");\n this.space();\n this.token(\"(\");\n this.print(node.test, node);\n this.token(\")\");\n this.space();\n\n const needsBlock =\n node.alternate && isIfStatement(getLastStatement(node.consequent));\n if (needsBlock) {\n this.token(\"{\");\n this.newline();\n this.indent();\n }\n\n this.printAndIndentOnComments(node.consequent, node);\n\n if (needsBlock) {\n this.dedent();\n this.newline();\n this.token(\"}\");\n }\n\n if (node.alternate) {\n if (this.endsWith(charCodes.rightCurlyBrace)) this.space();\n this.word(\"else\");\n this.space();\n this.printAndIndentOnComments(node.alternate, node);\n }\n}\n\n// Recursively get the last statement.\nfunction getLastStatement(statement: t.Statement): t.Statement {\n // @ts-expect-error: If statement.body is empty or not a Node, isStatement will return false\n const { body } = statement;\n if (isStatement(body) === false) {\n return statement;\n }\n\n return getLastStatement(body);\n}\n\nexport function ForStatement(this: Printer, node: t.ForStatement) {\n this.word(\"for\");\n this.space();\n this.token(\"(\");\n\n this.inForStatementInitCounter++;\n this.print(node.init, node);\n this.inForStatementInitCounter--;\n this.token(\";\");\n\n if (node.test) {\n this.space();\n this.print(node.test, node);\n }\n this.token(\";\");\n\n if (node.update) {\n this.space();\n this.print(node.update, node);\n }\n\n this.token(\")\");\n this.printBlock(node);\n}\n\nexport function WhileStatement(this: Printer, node: t.WhileStatement) {\n this.word(\"while\");\n this.space();\n this.token(\"(\");\n this.print(node.test, node);\n this.token(\")\");\n this.printBlock(node);\n}\n\nfunction ForXStatement(this: Printer, node: t.ForXStatement) {\n this.word(\"for\");\n this.space();\n const isForOf = node.type === \"ForOfStatement\";\n if (isForOf && node.await) {\n this.word(\"await\");\n this.space();\n }\n this.token(\"(\");\n this.print(node.left, node);\n this.space();\n this.word(isForOf ? \"of\" : \"in\");\n this.space();\n this.print(node.right, node);\n this.token(\")\");\n this.printBlock(node);\n}\n\nexport const ForInStatement = ForXStatement;\nexport const ForOfStatement = ForXStatement;\n\nexport function DoWhileStatement(this: Printer, node: t.DoWhileStatement) {\n this.word(\"do\");\n this.space();\n this.print(node.body, node);\n this.space();\n this.word(\"while\");\n this.space();\n this.token(\"(\");\n this.print(node.test, node);\n this.token(\")\");\n this.semicolon();\n}\n\nfunction printStatementAfterKeyword(\n printer: Printer,\n node: t.Node,\n parent: t.Node,\n isLabel: boolean,\n) {\n if (node) {\n printer.space();\n printer.printTerminatorless(node, parent, isLabel);\n }\n\n printer.semicolon();\n}\n\nexport function BreakStatement(this: Printer, node: t.ContinueStatement) {\n this.word(\"break\");\n printStatementAfterKeyword(this, node.label, node, true);\n}\n\nexport function ContinueStatement(this: Printer, node: t.ContinueStatement) {\n this.word(\"continue\");\n printStatementAfterKeyword(this, node.label, node, true);\n}\n\nexport function ReturnStatement(this: Printer, node: t.ReturnStatement) {\n this.word(\"return\");\n printStatementAfterKeyword(this, node.argument, node, false);\n}\n\nexport function ThrowStatement(this: Printer, node: t.ThrowStatement) {\n this.word(\"throw\");\n printStatementAfterKeyword(this, node.argument, node, false);\n}\n\nexport function LabeledStatement(this: Printer, node: t.LabeledStatement) {\n this.print(node.label, node);\n this.token(\":\");\n this.space();\n this.print(node.body, node);\n}\n\nexport function TryStatement(this: Printer, node: t.TryStatement) {\n this.word(\"try\");\n this.space();\n this.print(node.block, node);\n this.space();\n\n // Esprima bug puts the catch clause in a `handlers` array.\n // see https://code.google.com/p/esprima/issues/detail?id=433\n // We run into this from regenerator generated ast.\n // @ts-expect-error todo(flow->ts) should ast node type be updated to support this?\n if (node.handlers) {\n // @ts-expect-error todo(flow->ts) should ast node type be updated to support this?\n this.print(node.handlers[0], node);\n } else {\n this.print(node.handler, node);\n }\n\n if (node.finalizer) {\n this.space();\n this.word(\"finally\");\n this.space();\n this.print(node.finalizer, node);\n }\n}\n\nexport function CatchClause(this: Printer, node: t.CatchClause) {\n this.word(\"catch\");\n this.space();\n if (node.param) {\n this.token(\"(\");\n this.print(node.param, node);\n this.print(node.param.typeAnnotation, node);\n this.token(\")\");\n this.space();\n }\n this.print(node.body, node);\n}\n\nexport function SwitchStatement(this: Printer, node: t.SwitchStatement) {\n this.word(\"switch\");\n this.space();\n this.token(\"(\");\n this.print(node.discriminant, node);\n this.token(\")\");\n this.space();\n this.token(\"{\");\n\n this.printSequence(node.cases, node, {\n indent: true,\n addNewlines(leading, cas) {\n if (!leading && node.cases[node.cases.length - 1] === cas) return -1;\n },\n });\n\n this.token(\"}\");\n}\n\nexport function SwitchCase(this: Printer, node: t.SwitchCase) {\n if (node.test) {\n this.word(\"case\");\n this.space();\n this.print(node.test, node);\n this.token(\":\");\n } else {\n this.word(\"default\");\n this.token(\":\");\n }\n\n if (node.consequent.length) {\n this.newline();\n this.printSequence(node.consequent, node, { indent: true });\n }\n}\n\nexport function DebuggerStatement(this: Printer) {\n this.word(\"debugger\");\n this.semicolon();\n}\n\nexport function VariableDeclaration(\n this: Printer,\n node: t.VariableDeclaration,\n parent: t.Node,\n) {\n if (node.declare) {\n // TS\n this.word(\"declare\");\n this.space();\n }\n\n this.word(node.kind);\n this.space();\n\n let hasInits = false;\n // don't add whitespace to loop heads\n if (!isFor(parent)) {\n for (const declar of node.declarations) {\n if (declar.init) {\n // has an init so let's split it up over multiple lines\n hasInits = true;\n }\n }\n }\n\n //\n // use a pretty separator when we aren't in compact mode, have initializers and don't have retainLines on\n // this will format declarations like:\n //\n // let foo = \"bar\", bar = \"foo\";\n //\n // into\n //\n // let foo = \"bar\",\n // bar = \"foo\";\n //\n\n this.printList(node.declarations, node, {\n separator: hasInits\n ? function (this: Printer) {\n this.token(\",\");\n this.newline();\n }\n : undefined,\n indent: node.declarations.length > 1 ? true : false,\n });\n\n if (isFor(parent)) {\n // don't give semicolons to these nodes since they'll be inserted in the parent generator\n if (isForStatement(parent)) {\n if (parent.init === node) return;\n } else {\n if (parent.left === node) return;\n }\n }\n\n this.semicolon();\n}\n\nexport function VariableDeclarator(this: Printer, node: t.VariableDeclarator) {\n this.print(node.id, node);\n if (node.definite) this.token(\"!\"); // TS\n // @ts-expect-error todo(flow-ts) Property 'typeAnnotation' does not exist on type 'MemberExpression'.\n this.print(node.id.typeAnnotation, node);\n if (node.init) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.init, node);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AACA;;;EACEA,K;EACAC,c;EACAC,a;EACAC;;;AAKK,SAASC,aAAT,CAAsCC,IAAtC,EAA6D;EAClE,KAAKC,IAAL,CAAU,MAAV;EACA,KAAKC,KAAL;EACA,KAAKC,SAAL;EACA,KAAKC,KAAL,CAAWJ,IAAI,CAACK,MAAhB,EAAwBL,IAAxB;EACA,KAAKG,SAAL;EACA,KAAKG,UAAL,CAAgBN,IAAhB;AACD;;AAEM,SAASO,WAAT,CAAoCP,IAApC,EAAyD;EAC9D,KAAKC,IAAL,CAAU,IAAV;EACA,KAAKC,KAAL;EACA,KAAKC,SAAL;EACA,KAAKC,KAAL,CAAWJ,IAAI,CAACQ,IAAhB,EAAsBR,IAAtB;EACA,KAAKG,SAAL;EACA,KAAKD,KAAL;EAEA,MAAMO,UAAU,GACdT,IAAI,CAACU,SAAL,IAAkBb,aAAa,CAACc,gBAAgB,CAACX,IAAI,CAACY,UAAN,CAAjB,CADjC;;EAEA,IAAIH,UAAJ,EAAgB;IACd,KAAKN,SAAL;IACA,KAAKU,OAAL;IACA,KAAKC,MAAL;EACD;;EAED,KAAKC,wBAAL,CAA8Bf,IAAI,CAACY,UAAnC,EAA+CZ,IAA/C;;EAEA,IAAIS,UAAJ,EAAgB;IACd,KAAKO,MAAL;IACA,KAAKH,OAAL;IACA,KAAKV,SAAL;EACD;;EAED,IAAIH,IAAI,CAACU,SAAT,EAAoB;IAClB,IAAI,KAAKO,QAAL,KAAJ,EAA8C,KAAKf,KAAL;IAC9C,KAAKD,IAAL,CAAU,MAAV;IACA,KA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cAAc,CAACyC,MAAD,CAAlB,EAA4B;MAC1B,IAAIA,MAAM,CAACf,IAAP,KAAgBtB,IAApB,EAA0B;IAC3B,CAFD,MAEO;MACL,IAAIqC,MAAM,CAACR,IAAP,KAAgB7B,IAApB,EAA0B;IAC3B;EACF;;EAED,KAAKkC,SAAL;AACD;;AAEM,SAASwC,kBAAT,CAA2C1E,IAA3C,EAAuE;EAC5E,KAAKI,KAAL,CAAWJ,IAAI,CAAC2E,EAAhB,EAAoB3E,IAApB;EACA,IAAIA,IAAI,CAAC4E,QAAT,EAAmB,KAAKzE,SAAL;EAEnB,KAAKC,KAAL,CAAWJ,IAAI,CAAC2E,EAAL,CAAQrB,cAAnB,EAAmCtD,IAAnC;;EACA,IAAIA,IAAI,CAACsB,IAAT,EAAe;IACb,KAAKpB,KAAL;IACA,KAAKC,SAAL;IACA,KAAKD,KAAL;IACA,KAAKE,KAAL,CAAWJ,IAAI,CAACsB,IAAhB,EAAsBtB,IAAtB;EACD;AACF"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/template-literals.js b/node_modules/@babel/generator/lib/generators/template-literals.js new file mode 100644 index 0000000..6d38dd8 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/template-literals.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TaggedTemplateExpression = TaggedTemplateExpression; +exports.TemplateElement = TemplateElement; +exports.TemplateLiteral = TemplateLiteral; + +function TaggedTemplateExpression(node) { + this.print(node.tag, node); + this.print(node.typeParameters, node); + this.print(node.quasi, node); +} + +function TemplateElement(node, parent) { + const isFirst = parent.quasis[0] === node; + const isLast = parent.quasis[parent.quasis.length - 1] === node; + const value = (isFirst ? "`" : "}") + node.value.raw + (isLast ? "`" : "${"); + this.token(value, true); +} + +function TemplateLiteral(node) { + const quasis = node.quasis; + + for (let i = 0; i < quasis.length; i++) { + this.print(quasis[i], node); + + if (i + 1 < quasis.length) { + this.print(node.expressions[i], node); + } + } +} + +//# sourceMappingURL=template-literals.js.map diff --git a/node_modules/@babel/generator/lib/generators/template-literals.js.map b/node_modules/@babel/generator/lib/generators/template-literals.js.map new file mode 100644 index 0000000..27e01d1 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/template-literals.js.map @@ -0,0 +1 @@ +{"version":3,"names":["TaggedTemplateExpression","node","print","tag","typeParameters","quasi","TemplateElement","parent","isFirst","quasis","isLast","length","value","raw","token","TemplateLiteral","i","expressions"],"sources":["../../src/generators/template-literals.ts"],"sourcesContent":["import type Printer from \"../printer\";\nimport type * as t from \"@babel/types\";\n\nexport function TaggedTemplateExpression(\n this: Printer,\n node: t.TaggedTemplateExpression,\n) {\n this.print(node.tag, node);\n this.print(node.typeParameters, node); // TS\n this.print(node.quasi, node);\n}\n\nexport function TemplateElement(\n this: Printer,\n node: t.TemplateElement,\n parent: t.TemplateLiteral,\n) {\n const isFirst = parent.quasis[0] === node;\n const isLast = parent.quasis[parent.quasis.length - 1] === node;\n\n const value = (isFirst ? \"`\" : \"}\") + node.value.raw + (isLast ? \"`\" : \"${\");\n\n this.token(value, true);\n}\n\nexport function TemplateLiteral(this: Printer, node: t.TemplateLiteral) {\n const quasis = node.quasis;\n\n for (let i = 0; i < quasis.length; i++) {\n this.print(quasis[i], node);\n\n if (i + 1 < quasis.length) {\n this.print(node.expressions[i], node);\n }\n }\n}\n"],"mappings":";;;;;;;;;AAGO,SAASA,wBAAT,CAELC,IAFK,EAGL;EACA,KAAKC,KAAL,CAAWD,IAAI,CAACE,GAAhB,EAAqBF,IAArB;EACA,KAAKC,KAAL,CAAWD,IAAI,CAACG,cAAhB,EAAgCH,IAAhC;EACA,KAAKC,KAAL,CAAWD,IAAI,CAACI,KAAhB,EAAuBJ,IAAvB;AACD;;AAEM,SAASK,eAAT,CAELL,IAFK,EAGLM,MAHK,EAIL;EACA,MAAMC,OAAO,GAAGD,MAAM,CAACE,MAAP,CAAc,CAAd,MAAqBR,IAArC;EACA,MAAMS,MAAM,GAAGH,MAAM,CAACE,MAAP,CAAcF,MAAM,CAACE,MAAP,CAAcE,MAAd,GAAuB,CAArC,MAA4CV,IAA3D;EAEA,MAAMW,KAAK,GAAG,CAACJ,OAAO,GAAG,GAAH,GAAS,GAAjB,IAAwBP,IAAI,CAACW,KAAL,CAAWC,GAAnC,IAA0CH,MAAM,GAAG,GAAH,GAAS,IAAzD,CAAd;EAEA,KAAKI,KAAL,CAAWF,KAAX,EAAkB,IAAlB;AACD;;AAEM,SAASG,eAAT,CAAwCd,IAAxC,EAAiE;EACtE,MAAMQ,MAAM,GAAGR,IAAI,CAACQ,MAApB;;EAEA,KAAK,IAAIO,CAAC,GAAG,CAAb,EAAgBA,CAAC,GAAGP,MAAM,CAACE,MAA3B,EAAmCK,CAAC,EAApC,EAAwC;IACtC,KAAKd,KAAL,CAAWO,MAAM,CAACO,CAAD,CAAjB,EAAsBf,IAAtB;;IAEA,IAAIe,CAAC,GAAG,CAAJ,GAAQP,MAAM,CAACE,MAAnB,EAA2B;MACzB,KAAKT,KAAL,CAAWD,IAAI,CAACgB,WAAL,CAAiBD,CAAjB,CAAX,EAAgCf,IAAhC;IACD;EACF;AACF"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/types.js b/node_modules/@babel/generator/lib/generators/types.js new file mode 100644 index 0000000..5443958 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/types.js @@ -0,0 +1,277 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ArgumentPlaceholder = ArgumentPlaceholder; +exports.ArrayPattern = exports.ArrayExpression = ArrayExpression; +exports.BigIntLiteral = BigIntLiteral; +exports.BooleanLiteral = BooleanLiteral; +exports.DecimalLiteral = DecimalLiteral; +exports.Identifier = Identifier; +exports.NullLiteral = NullLiteral; +exports.NumericLiteral = NumericLiteral; +exports.ObjectPattern = exports.ObjectExpression = ObjectExpression; +exports.ObjectMethod = ObjectMethod; +exports.ObjectProperty = ObjectProperty; +exports.PipelineBareFunction = PipelineBareFunction; +exports.PipelinePrimaryTopicReference = PipelinePrimaryTopicReference; +exports.PipelineTopicExpression = PipelineTopicExpression; +exports.RecordExpression = RecordExpression; +exports.RegExpLiteral = RegExpLiteral; +exports.SpreadElement = exports.RestElement = RestElement; +exports.StringLiteral = StringLiteral; +exports.TopicReference = TopicReference; +exports.TupleExpression = TupleExpression; + +var _t = require("@babel/types"); + +var _jsesc = require("jsesc"); + +const { + isAssignmentPattern, + isIdentifier +} = _t; + +function Identifier(node) { + this.word(node.name); +} + +function ArgumentPlaceholder() { + this.tokenChar(63); +} + +function RestElement(node) { + this.token("..."); + this.print(node.argument, node); +} + +function ObjectExpression(node) { + const props = node.properties; + this.tokenChar(123); + this.printInnerComments(node); + + if (props.length) { + this.space(); + this.printList(props, node, { + indent: true, + statement: true + }); + this.space(); + } + + this.sourceWithOffset("end", node.loc, 0, -1); + this.tokenChar(125); +} + +function ObjectMethod(node) { + this.printJoin(node.decorators, node); + + this._methodHead(node); + + this.space(); + this.print(node.body, node); +} + +function ObjectProperty(node) { + this.printJoin(node.decorators, node); + + if (node.computed) { + this.tokenChar(91); + this.print(node.key, node); + this.tokenChar(93); + } else { + if (isAssignmentPattern(node.value) && isIdentifier(node.key) && node.key.name === node.value.left.name) { + this.print(node.value, node); + return; + } + + this.print(node.key, node); + + if (node.shorthand && isIdentifier(node.key) && isIdentifier(node.value) && node.key.name === node.value.name) { + return; + } + } + + this.tokenChar(58); + this.space(); + this.print(node.value, node); +} + +function ArrayExpression(node) { + const elems = node.elements; + const len = elems.length; + this.tokenChar(91); + this.printInnerComments(node); + + for (let i = 0; i < elems.length; i++) { + const elem = elems[i]; + + if (elem) { + if (i > 0) this.space(); + this.print(elem, node); + if (i < len - 1) this.tokenChar(44); + } else { + this.tokenChar(44); + } + } + + this.tokenChar(93); +} + +function RecordExpression(node) { + const props = node.properties; + let startToken; + let endToken; + + if (this.format.recordAndTupleSyntaxType === "bar") { + startToken = "{|"; + endToken = "|}"; + } else if (this.format.recordAndTupleSyntaxType !== "hash" && this.format.recordAndTupleSyntaxType != null) { + throw new Error(`The "recordAndTupleSyntaxType" generator option must be "bar" or "hash" (${JSON.stringify(this.format.recordAndTupleSyntaxType)} received).`); + } else { + startToken = "#{"; + endToken = "}"; + } + + this.token(startToken); + this.printInnerComments(node); + + if (props.length) { + this.space(); + this.printList(props, node, { + indent: true, + statement: true + }); + this.space(); + } + + this.token(endToken); +} + +function TupleExpression(node) { + const elems = node.elements; + const len = elems.length; + let startToken; + let endToken; + + if (this.format.recordAndTupleSyntaxType === "bar") { + startToken = "[|"; + endToken = "|]"; + } else if (this.format.recordAndTupleSyntaxType === "hash") { + startToken = "#["; + endToken = "]"; + } else { + throw new Error(`${this.format.recordAndTupleSyntaxType} is not a valid recordAndTuple syntax type`); + } + + this.token(startToken); + this.printInnerComments(node); + + for (let i = 0; i < elems.length; i++) { + const elem = elems[i]; + + if (elem) { + if (i > 0) this.space(); + this.print(elem, node); + if (i < len - 1) this.tokenChar(44); + } + } + + this.token(endToken); +} + +function RegExpLiteral(node) { + this.word(`/${node.pattern}/${node.flags}`); +} + +function BooleanLiteral(node) { + this.word(node.value ? "true" : "false"); +} + +function NullLiteral() { + this.word("null"); +} + +function NumericLiteral(node) { + const raw = this.getPossibleRaw(node); + const opts = this.format.jsescOption; + const value = node.value + ""; + + if (opts.numbers) { + this.number(_jsesc(node.value, opts)); + } else if (raw == null) { + this.number(value); + } else if (this.format.minified) { + this.number(raw.length < value.length ? raw : value); + } else { + this.number(raw); + } +} + +function StringLiteral(node) { + const raw = this.getPossibleRaw(node); + + if (!this.format.minified && raw !== undefined) { + this.token(raw); + return; + } + + const val = _jsesc(node.value, Object.assign(this.format.jsescOption, this.format.jsonCompatibleStrings && { + json: true + })); + + return this.token(val); +} + +function BigIntLiteral(node) { + const raw = this.getPossibleRaw(node); + + if (!this.format.minified && raw !== undefined) { + this.word(raw); + return; + } + + this.word(node.value + "n"); +} + +function DecimalLiteral(node) { + const raw = this.getPossibleRaw(node); + + if (!this.format.minified && raw !== undefined) { + this.word(raw); + return; + } + + this.word(node.value + "m"); +} + +const validTopicTokenSet = new Set(["^^", "@@", "^", "%", "#"]); + +function TopicReference() { + const { + topicToken + } = this.format; + + if (validTopicTokenSet.has(topicToken)) { + this.token(topicToken); + } else { + const givenTopicTokenJSON = JSON.stringify(topicToken); + const validTopics = Array.from(validTopicTokenSet, v => JSON.stringify(v)); + throw new Error(`The "topicToken" generator option must be one of ` + `${validTopics.join(", ")} (${givenTopicTokenJSON} received instead).`); + } +} + +function PipelineTopicExpression(node) { + this.print(node.expression, node); +} + +function PipelineBareFunction(node) { + this.print(node.callee, node); +} + +function PipelinePrimaryTopicReference() { + this.tokenChar(35); +} + +//# sourceMappingURL=types.js.map diff --git a/node_modules/@babel/generator/lib/generators/types.js.map b/node_modules/@babel/generator/lib/generators/types.js.map new file mode 100644 index 0000000..4a1d25a --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/types.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isAssignmentPattern","isIdentifier","Identifier","node","word","name","ArgumentPlaceholder","token","RestElement","print","argument","ObjectExpression","props","properties","printInnerComments","length","space","printList","indent","statement","sourceWithOffset","loc","ObjectMethod","printJoin","decorators","_methodHead","body","ObjectProperty","computed","key","value","left","shorthand","ArrayExpression","elems","elements","len","i","elem","RecordExpression","startToken","endToken","format","recordAndTupleSyntaxType","Error","JSON","stringify","TupleExpression","RegExpLiteral","pattern","flags","BooleanLiteral","NullLiteral","NumericLiteral","raw","getPossibleRaw","opts","jsescOption","numbers","number","jsesc","minified","StringLiteral","undefined","val","Object","assign","jsonCompatibleStrings","json","BigIntLiteral","DecimalLiteral","validTopicTokenSet","Set","TopicReference","topicToken","has","givenTopicTokenJSON","validTopics","Array","from","v","join","PipelineTopicExpression","expression","PipelineBareFunction","callee","PipelinePrimaryTopicReference"],"sources":["../../src/generators/types.ts"],"sourcesContent":["import type Printer from \"../printer\";\nimport { isAssignmentPattern, isIdentifier } from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nimport jsesc from \"jsesc\";\n\nexport function Identifier(this: Printer, node: t.Identifier) {\n this.word(node.name);\n}\n\nexport function ArgumentPlaceholder(this: Printer) {\n this.token(\"?\");\n}\n\nexport function RestElement(this: Printer, node: t.RestElement) {\n this.token(\"...\");\n this.print(node.argument, node);\n}\n\nexport { RestElement as SpreadElement };\n\nexport function ObjectExpression(this: Printer, node: t.ObjectExpression) {\n const props = node.properties;\n\n this.token(\"{\");\n this.printInnerComments(node);\n\n if (props.length) {\n this.space();\n this.printList(props, node, { indent: true, statement: true });\n this.space();\n }\n\n this.sourceWithOffset(\"end\", node.loc, 0, -1);\n\n this.token(\"}\");\n}\n\nexport { ObjectExpression as ObjectPattern };\n\nexport function ObjectMethod(this: Printer, node: t.ObjectMethod) {\n this.printJoin(node.decorators, node);\n this._methodHead(node);\n this.space();\n this.print(node.body, node);\n}\n\nexport function ObjectProperty(this: Printer, node: t.ObjectProperty) {\n this.printJoin(node.decorators, node);\n\n if (node.computed) {\n this.token(\"[\");\n this.print(node.key, node);\n this.token(\"]\");\n } else {\n // print `({ foo: foo = 5 } = {})` as `({ foo = 5 } = {});`\n if (\n isAssignmentPattern(node.value) &&\n isIdentifier(node.key) &&\n // @ts-expect-error todo(flow->ts) `.name` does not exist on some types in union\n node.key.name === node.value.left.name\n ) {\n this.print(node.value, node);\n return;\n }\n\n this.print(node.key, node);\n\n // shorthand!\n if (\n node.shorthand &&\n isIdentifier(node.key) &&\n isIdentifier(node.value) &&\n node.key.name === node.value.name\n ) {\n return;\n }\n }\n\n this.token(\":\");\n this.space();\n this.print(node.value, node);\n}\n\nexport function ArrayExpression(this: Printer, node: t.ArrayExpression) {\n const elems = node.elements;\n const len = elems.length;\n\n this.token(\"[\");\n this.printInnerComments(node);\n\n for (let i = 0; i < elems.length; i++) {\n const elem = elems[i];\n if (elem) {\n if (i > 0) this.space();\n this.print(elem, node);\n if (i < len - 1) this.token(\",\");\n } else {\n // If the array expression ends with a hole, that hole\n // will be ignored by the interpreter, but if it ends with\n // two (or more) holes, we need to write out two (or more)\n // commas so that the resulting code is interpreted with\n // both (all) of the holes.\n this.token(\",\");\n }\n }\n\n this.token(\"]\");\n}\n\nexport { ArrayExpression as ArrayPattern };\n\nexport function RecordExpression(this: Printer, node: t.RecordExpression) {\n const props = node.properties;\n\n let startToken;\n let endToken;\n if (this.format.recordAndTupleSyntaxType === \"bar\") {\n startToken = \"{|\";\n endToken = \"|}\";\n } else if (\n this.format.recordAndTupleSyntaxType !== \"hash\" &&\n this.format.recordAndTupleSyntaxType != null\n ) {\n throw new Error(\n `The \"recordAndTupleSyntaxType\" generator option must be \"bar\" or \"hash\" (${JSON.stringify(\n this.format.recordAndTupleSyntaxType,\n )} received).`,\n );\n } else {\n startToken = \"#{\";\n endToken = \"}\";\n }\n\n this.token(startToken);\n this.printInnerComments(node);\n\n if (props.length) {\n this.space();\n this.printList(props, node, { indent: true, statement: true });\n this.space();\n }\n this.token(endToken);\n}\n\nexport function TupleExpression(this: Printer, node: t.TupleExpression) {\n const elems = node.elements;\n const len = elems.length;\n\n let startToken;\n let endToken;\n if (this.format.recordAndTupleSyntaxType === \"bar\") {\n startToken = \"[|\";\n endToken = \"|]\";\n } else if (this.format.recordAndTupleSyntaxType === \"hash\") {\n startToken = \"#[\";\n endToken = \"]\";\n } else {\n throw new Error(\n `${this.format.recordAndTupleSyntaxType} is not a valid recordAndTuple syntax type`,\n );\n }\n\n this.token(startToken);\n this.printInnerComments(node);\n\n for (let i = 0; i < elems.length; i++) {\n const elem = elems[i];\n if (elem) {\n if (i > 0) this.space();\n this.print(elem, node);\n if (i < len - 1) this.token(\",\");\n }\n }\n\n this.token(endToken);\n}\n\nexport function RegExpLiteral(this: Printer, node: t.RegExpLiteral) {\n this.word(`/${node.pattern}/${node.flags}`);\n}\n\nexport function BooleanLiteral(this: Printer, node: t.BooleanLiteral) {\n this.word(node.value ? \"true\" : \"false\");\n}\n\nexport function NullLiteral(this: Printer) {\n this.word(\"null\");\n}\n\nexport function NumericLiteral(this: Printer, node: t.NumericLiteral) {\n const raw = this.getPossibleRaw(node);\n const opts = this.format.jsescOption;\n const value = node.value + \"\";\n if (opts.numbers) {\n this.number(jsesc(node.value, opts));\n } else if (raw == null) {\n this.number(value); // normalize\n } else if (this.format.minified) {\n this.number(raw.length < value.length ? raw : value);\n } else {\n this.number(raw);\n }\n}\n\nexport function StringLiteral(this: Printer, node: t.StringLiteral) {\n const raw = this.getPossibleRaw(node);\n if (!this.format.minified && raw !== undefined) {\n this.token(raw);\n return;\n }\n\n const val = jsesc(\n node.value,\n process.env.BABEL_8_BREAKING\n ? this.format.jsescOption\n : Object.assign(\n this.format.jsescOption,\n this.format.jsonCompatibleStrings && { json: true },\n ),\n );\n\n return this.token(val);\n}\n\nexport function BigIntLiteral(this: Printer, node: t.BigIntLiteral) {\n const raw = this.getPossibleRaw(node);\n if (!this.format.minified && raw !== undefined) {\n this.word(raw);\n return;\n }\n this.word(node.value + \"n\");\n}\n\nexport function DecimalLiteral(this: Printer, node: t.DecimalLiteral) {\n const raw = this.getPossibleRaw(node);\n if (!this.format.minified && raw !== undefined) {\n this.word(raw);\n return;\n }\n this.word(node.value + \"m\");\n}\n\n// Hack pipe operator\nconst validTopicTokenSet = new Set([\"^^\", \"@@\", \"^\", \"%\", \"#\"]);\nexport function TopicReference(this: Printer) {\n const { topicToken } = this.format;\n\n if (validTopicTokenSet.has(topicToken)) {\n this.token(topicToken);\n } else {\n const givenTopicTokenJSON = JSON.stringify(topicToken);\n const validTopics = Array.from(validTopicTokenSet, v => JSON.stringify(v));\n throw new Error(\n `The \"topicToken\" generator option must be one of ` +\n `${validTopics.join(\", \")} (${givenTopicTokenJSON} received instead).`,\n );\n }\n}\n\n// Smart-mix pipe operator\nexport function PipelineTopicExpression(\n this: Printer,\n node: t.PipelineTopicExpression,\n) {\n this.print(node.expression, node);\n}\n\nexport function PipelineBareFunction(\n this: Printer,\n node: t.PipelineBareFunction,\n) {\n this.print(node.callee, node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,EAGL;EACA,KAAKM,KAAL,CAAWN,IAAI,CAACkF,MAAhB,EAAwBlF,IAAxB;AACD;;AAEM,SAASmF,6BAAT,GAAsD;EAC3D,KAAK/E,SAAL;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/generators/typescript.js b/node_modules/@babel/generator/lib/generators/typescript.js new file mode 100644 index 0000000..f0d409e --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/typescript.js @@ -0,0 +1,835 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TSAnyKeyword = TSAnyKeyword; +exports.TSArrayType = TSArrayType; +exports.TSAsExpression = TSAsExpression; +exports.TSBigIntKeyword = TSBigIntKeyword; +exports.TSBooleanKeyword = TSBooleanKeyword; +exports.TSCallSignatureDeclaration = TSCallSignatureDeclaration; +exports.TSConditionalType = TSConditionalType; +exports.TSConstructSignatureDeclaration = TSConstructSignatureDeclaration; +exports.TSConstructorType = TSConstructorType; +exports.TSDeclareFunction = TSDeclareFunction; +exports.TSDeclareMethod = TSDeclareMethod; +exports.TSEnumDeclaration = TSEnumDeclaration; +exports.TSEnumMember = TSEnumMember; +exports.TSExportAssignment = TSExportAssignment; +exports.TSExpressionWithTypeArguments = TSExpressionWithTypeArguments; +exports.TSExternalModuleReference = TSExternalModuleReference; +exports.TSFunctionType = TSFunctionType; +exports.TSImportEqualsDeclaration = TSImportEqualsDeclaration; +exports.TSImportType = TSImportType; +exports.TSIndexSignature = TSIndexSignature; +exports.TSIndexedAccessType = TSIndexedAccessType; +exports.TSInferType = TSInferType; +exports.TSInstantiationExpression = TSInstantiationExpression; +exports.TSInterfaceBody = TSInterfaceBody; +exports.TSInterfaceDeclaration = TSInterfaceDeclaration; +exports.TSIntersectionType = TSIntersectionType; +exports.TSIntrinsicKeyword = TSIntrinsicKeyword; +exports.TSLiteralType = TSLiteralType; +exports.TSMappedType = TSMappedType; +exports.TSMethodSignature = TSMethodSignature; +exports.TSModuleBlock = TSModuleBlock; +exports.TSModuleDeclaration = TSModuleDeclaration; +exports.TSNamedTupleMember = TSNamedTupleMember; +exports.TSNamespaceExportDeclaration = TSNamespaceExportDeclaration; +exports.TSNeverKeyword = TSNeverKeyword; +exports.TSNonNullExpression = TSNonNullExpression; +exports.TSNullKeyword = TSNullKeyword; +exports.TSNumberKeyword = TSNumberKeyword; +exports.TSObjectKeyword = TSObjectKeyword; +exports.TSOptionalType = TSOptionalType; +exports.TSParameterProperty = TSParameterProperty; +exports.TSParenthesizedType = TSParenthesizedType; +exports.TSPropertySignature = TSPropertySignature; +exports.TSQualifiedName = TSQualifiedName; +exports.TSRestType = TSRestType; +exports.TSStringKeyword = TSStringKeyword; +exports.TSSymbolKeyword = TSSymbolKeyword; +exports.TSThisType = TSThisType; +exports.TSTupleType = TSTupleType; +exports.TSTypeAliasDeclaration = TSTypeAliasDeclaration; +exports.TSTypeAnnotation = TSTypeAnnotation; +exports.TSTypeAssertion = TSTypeAssertion; +exports.TSTypeLiteral = TSTypeLiteral; +exports.TSTypeOperator = TSTypeOperator; +exports.TSTypeParameter = TSTypeParameter; +exports.TSTypeParameterDeclaration = exports.TSTypeParameterInstantiation = TSTypeParameterInstantiation; +exports.TSTypePredicate = TSTypePredicate; +exports.TSTypeQuery = TSTypeQuery; +exports.TSTypeReference = TSTypeReference; +exports.TSUndefinedKeyword = TSUndefinedKeyword; +exports.TSUnionType = TSUnionType; +exports.TSUnknownKeyword = TSUnknownKeyword; +exports.TSVoidKeyword = TSVoidKeyword; +exports.tsPrintClassMemberModifiers = tsPrintClassMemberModifiers; +exports.tsPrintFunctionOrConstructorType = tsPrintFunctionOrConstructorType; +exports.tsPrintPropertyOrMethodName = tsPrintPropertyOrMethodName; +exports.tsPrintSignatureDeclarationBase = tsPrintSignatureDeclarationBase; +exports.tsPrintTypeLiteralOrInterfaceBody = tsPrintTypeLiteralOrInterfaceBody; + +function TSTypeAnnotation(node) { + this.tokenChar(58); + this.space(); + if (node.optional) this.tokenChar(63); + this.print(node.typeAnnotation, node); +} + +function TSTypeParameterInstantiation(node, parent) { + this.tokenChar(60); + this.printList(node.params, node, {}); + + if (parent.type === "ArrowFunctionExpression" && node.params.length === 1) { + this.tokenChar(44); + } + + this.tokenChar(62); +} + +function TSTypeParameter(node) { + if (node.in) { + this.word("in"); + this.space(); + } + + if (node.out) { + this.word("out"); + this.space(); + } + + this.word(node.name); + + if (node.constraint) { + this.space(); + this.word("extends"); + this.space(); + this.print(node.constraint, node); + } + + if (node.default) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.default, node); + } +} + +function TSParameterProperty(node) { + if (node.accessibility) { + this.word(node.accessibility); + this.space(); + } + + if (node.readonly) { + this.word("readonly"); + this.space(); + } + + this._param(node.parameter); +} + +function TSDeclareFunction(node) { + if (node.declare) { + this.word("declare"); + this.space(); + } + + this._functionHead(node); + + this.tokenChar(59); +} + +function TSDeclareMethod(node) { + this._classMethodHead(node); + + this.tokenChar(59); +} + +function TSQualifiedName(node) { + this.print(node.left, node); + this.tokenChar(46); + this.print(node.right, node); +} + +function TSCallSignatureDeclaration(node) { + this.tsPrintSignatureDeclarationBase(node); + this.tokenChar(59); +} + +function TSConstructSignatureDeclaration(node) { + this.word("new"); + this.space(); + this.tsPrintSignatureDeclarationBase(node); + this.tokenChar(59); +} + +function TSPropertySignature(node) { + const { + readonly, + initializer + } = node; + + if (readonly) { + this.word("readonly"); + this.space(); + } + + this.tsPrintPropertyOrMethodName(node); + this.print(node.typeAnnotation, node); + + if (initializer) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(initializer, node); + } + + this.tokenChar(59); +} + +function tsPrintPropertyOrMethodName(node) { + if (node.computed) { + this.tokenChar(91); + } + + this.print(node.key, node); + + if (node.computed) { + this.tokenChar(93); + } + + if (node.optional) { + this.tokenChar(63); + } +} + +function TSMethodSignature(node) { + const { + kind + } = node; + + if (kind === "set" || kind === "get") { + this.word(kind); + this.space(); + } + + this.tsPrintPropertyOrMethodName(node); + this.tsPrintSignatureDeclarationBase(node); + this.tokenChar(59); +} + +function TSIndexSignature(node) { + const { + readonly, + static: isStatic + } = node; + + if (isStatic) { + this.word("static"); + this.space(); + } + + if (readonly) { + this.word("readonly"); + this.space(); + } + + this.tokenChar(91); + + this._parameters(node.parameters, node); + + this.tokenChar(93); + this.print(node.typeAnnotation, node); + this.tokenChar(59); +} + +function TSAnyKeyword() { + this.word("any"); +} + +function TSBigIntKeyword() { + this.word("bigint"); +} + +function TSUnknownKeyword() { + this.word("unknown"); +} + +function TSNumberKeyword() { + this.word("number"); +} + +function TSObjectKeyword() { + this.word("object"); +} + +function TSBooleanKeyword() { + this.word("boolean"); +} + +function TSStringKeyword() { + this.word("string"); +} + +function TSSymbolKeyword() { + this.word("symbol"); +} + +function TSVoidKeyword() { + this.word("void"); +} + +function TSUndefinedKeyword() { + this.word("undefined"); +} + +function TSNullKeyword() { + this.word("null"); +} + +function TSNeverKeyword() { + this.word("never"); +} + +function TSIntrinsicKeyword() { + this.word("intrinsic"); +} + +function TSThisType() { + this.word("this"); +} + +function TSFunctionType(node) { + this.tsPrintFunctionOrConstructorType(node); +} + +function TSConstructorType(node) { + if (node.abstract) { + this.word("abstract"); + this.space(); + } + + this.word("new"); + this.space(); + this.tsPrintFunctionOrConstructorType(node); +} + +function tsPrintFunctionOrConstructorType(node) { + const { + typeParameters + } = node; + const parameters = node.parameters; + this.print(typeParameters, node); + this.tokenChar(40); + + this._parameters(parameters, node); + + this.tokenChar(41); + this.space(); + this.token("=>"); + this.space(); + const returnType = node.typeAnnotation; + this.print(returnType.typeAnnotation, node); +} + +function TSTypeReference(node) { + this.print(node.typeName, node, true); + this.print(node.typeParameters, node, true); +} + +function TSTypePredicate(node) { + if (node.asserts) { + this.word("asserts"); + this.space(); + } + + this.print(node.parameterName); + + if (node.typeAnnotation) { + this.space(); + this.word("is"); + this.space(); + this.print(node.typeAnnotation.typeAnnotation); + } +} + +function TSTypeQuery(node) { + this.word("typeof"); + this.space(); + this.print(node.exprName); + + if (node.typeParameters) { + this.print(node.typeParameters, node); + } +} + +function TSTypeLiteral(node) { + this.tsPrintTypeLiteralOrInterfaceBody(node.members, node); +} + +function tsPrintTypeLiteralOrInterfaceBody(members, node) { + tsPrintBraced(this, members, node); +} + +function tsPrintBraced(printer, members, node) { + printer.token("{"); + + if (members.length) { + printer.indent(); + printer.newline(); + + for (const member of members) { + printer.print(member, node); + printer.newline(); + } + + printer.dedent(); + } + + printer.sourceWithOffset("end", node.loc, 0, -1); + printer.rightBrace(); +} + +function TSArrayType(node) { + this.print(node.elementType, node, true); + this.token("[]"); +} + +function TSTupleType(node) { + this.tokenChar(91); + this.printList(node.elementTypes, node); + this.tokenChar(93); +} + +function TSOptionalType(node) { + this.print(node.typeAnnotation, node); + this.tokenChar(63); +} + +function TSRestType(node) { + this.token("..."); + this.print(node.typeAnnotation, node); +} + +function TSNamedTupleMember(node) { + this.print(node.label, node); + if (node.optional) this.tokenChar(63); + this.tokenChar(58); + this.space(); + this.print(node.elementType, node); +} + +function TSUnionType(node) { + tsPrintUnionOrIntersectionType(this, node, "|"); +} + +function TSIntersectionType(node) { + tsPrintUnionOrIntersectionType(this, node, "&"); +} + +function tsPrintUnionOrIntersectionType(printer, node, sep) { + printer.printJoin(node.types, node, { + separator() { + this.space(); + this.token(sep); + this.space(); + } + + }); +} + +function TSConditionalType(node) { + this.print(node.checkType); + this.space(); + this.word("extends"); + this.space(); + this.print(node.extendsType); + this.space(); + this.tokenChar(63); + this.space(); + this.print(node.trueType); + this.space(); + this.tokenChar(58); + this.space(); + this.print(node.falseType); +} + +function TSInferType(node) { + this.token("infer"); + this.space(); + this.print(node.typeParameter); +} + +function TSParenthesizedType(node) { + this.tokenChar(40); + this.print(node.typeAnnotation, node); + this.tokenChar(41); +} + +function TSTypeOperator(node) { + this.word(node.operator); + this.space(); + this.print(node.typeAnnotation, node); +} + +function TSIndexedAccessType(node) { + this.print(node.objectType, node, true); + this.tokenChar(91); + this.print(node.indexType, node); + this.tokenChar(93); +} + +function TSMappedType(node) { + const { + nameType, + optional, + readonly, + typeParameter + } = node; + this.tokenChar(123); + this.space(); + + if (readonly) { + tokenIfPlusMinus(this, readonly); + this.word("readonly"); + this.space(); + } + + this.tokenChar(91); + this.word(typeParameter.name); + this.space(); + this.word("in"); + this.space(); + this.print(typeParameter.constraint, typeParameter); + + if (nameType) { + this.space(); + this.word("as"); + this.space(); + this.print(nameType, node); + } + + this.tokenChar(93); + + if (optional) { + tokenIfPlusMinus(this, optional); + this.tokenChar(63); + } + + this.tokenChar(58); + this.space(); + this.print(node.typeAnnotation, node); + this.space(); + this.tokenChar(125); +} + +function tokenIfPlusMinus(self, tok) { + if (tok !== true) { + self.token(tok); + } +} + +function TSLiteralType(node) { + this.print(node.literal, node); +} + +function TSExpressionWithTypeArguments(node) { + this.print(node.expression, node); + this.print(node.typeParameters, node); +} + +function TSInterfaceDeclaration(node) { + const { + declare, + id, + typeParameters, + extends: extendz, + body + } = node; + + if (declare) { + this.word("declare"); + this.space(); + } + + this.word("interface"); + this.space(); + this.print(id, node); + this.print(typeParameters, node); + + if (extendz != null && extendz.length) { + this.space(); + this.word("extends"); + this.space(); + this.printList(extendz, node); + } + + this.space(); + this.print(body, node); +} + +function TSInterfaceBody(node) { + this.tsPrintTypeLiteralOrInterfaceBody(node.body, node); +} + +function TSTypeAliasDeclaration(node) { + const { + declare, + id, + typeParameters, + typeAnnotation + } = node; + + if (declare) { + this.word("declare"); + this.space(); + } + + this.word("type"); + this.space(); + this.print(id, node); + this.print(typeParameters, node); + this.space(); + this.tokenChar(61); + this.space(); + this.print(typeAnnotation, node); + this.tokenChar(59); +} + +function TSAsExpression(node) { + const { + expression, + typeAnnotation + } = node; + this.print(expression, node); + this.space(); + this.word("as"); + this.space(); + this.print(typeAnnotation, node); +} + +function TSTypeAssertion(node) { + const { + typeAnnotation, + expression + } = node; + this.tokenChar(60); + this.print(typeAnnotation, node); + this.tokenChar(62); + this.space(); + this.print(expression, node); +} + +function TSInstantiationExpression(node) { + this.print(node.expression, node); + this.print(node.typeParameters, node); +} + +function TSEnumDeclaration(node) { + const { + declare, + const: isConst, + id, + members + } = node; + + if (declare) { + this.word("declare"); + this.space(); + } + + if (isConst) { + this.word("const"); + this.space(); + } + + this.word("enum"); + this.space(); + this.print(id, node); + this.space(); + tsPrintBraced(this, members, node); +} + +function TSEnumMember(node) { + const { + id, + initializer + } = node; + this.print(id, node); + + if (initializer) { + this.space(); + this.tokenChar(61); + this.space(); + this.print(initializer, node); + } + + this.tokenChar(44); +} + +function TSModuleDeclaration(node) { + const { + declare, + id + } = node; + + if (declare) { + this.word("declare"); + this.space(); + } + + if (!node.global) { + this.word(id.type === "Identifier" ? "namespace" : "module"); + this.space(); + } + + this.print(id, node); + + if (!node.body) { + this.tokenChar(59); + return; + } + + let body = node.body; + + while (body.type === "TSModuleDeclaration") { + this.tokenChar(46); + this.print(body.id, body); + body = body.body; + } + + this.space(); + this.print(body, node); +} + +function TSModuleBlock(node) { + tsPrintBraced(this, node.body, node); +} + +function TSImportType(node) { + const { + argument, + qualifier, + typeParameters + } = node; + this.word("import"); + this.tokenChar(40); + this.print(argument, node); + this.tokenChar(41); + + if (qualifier) { + this.tokenChar(46); + this.print(qualifier, node); + } + + if (typeParameters) { + this.print(typeParameters, node); + } +} + +function TSImportEqualsDeclaration(node) { + const { + isExport, + id, + moduleReference + } = node; + + if (isExport) { + this.word("export"); + this.space(); + } + + this.word("import"); + this.space(); + this.print(id, node); + this.space(); + this.tokenChar(61); + this.space(); + this.print(moduleReference, node); + this.tokenChar(59); +} + +function TSExternalModuleReference(node) { + this.token("require("); + this.print(node.expression, node); + this.tokenChar(41); +} + +function TSNonNullExpression(node) { + this.print(node.expression, node); + this.tokenChar(33); +} + +function TSExportAssignment(node) { + this.word("export"); + this.space(); + this.tokenChar(61); + this.space(); + this.print(node.expression, node); + this.tokenChar(59); +} + +function TSNamespaceExportDeclaration(node) { + this.word("export"); + this.space(); + this.word("as"); + this.space(); + this.word("namespace"); + this.space(); + this.print(node.id, node); +} + +function tsPrintSignatureDeclarationBase(node) { + const { + typeParameters + } = node; + const parameters = node.parameters; + this.print(typeParameters, node); + this.tokenChar(40); + + this._parameters(parameters, node); + + this.tokenChar(41); + const returnType = node.typeAnnotation; + this.print(returnType, node); +} + +function tsPrintClassMemberModifiers(node) { + const isField = node.type === "ClassAccessorProperty" || node.type === "ClassProperty"; + + if (isField && node.declare) { + this.word("declare"); + this.space(); + } + + if (node.accessibility) { + this.word(node.accessibility); + this.space(); + } + + if (node.static) { + this.word("static"); + this.space(); + } + + if (node.override) { + this.word("override"); + this.space(); + } + + if (node.abstract) { + this.word("abstract"); + this.space(); + } + + if (isField && node.readonly) { + this.word("readonly"); + this.space(); + } +} + +//# sourceMappingURL=typescript.js.map diff --git a/node_modules/@babel/generator/lib/generators/typescript.js.map b/node_modules/@babel/generator/lib/generators/typescript.js.map new file mode 100644 index 0000000..54946d4 --- /dev/null +++ b/node_modules/@babel/generator/lib/generators/typescript.js.map @@ -0,0 +1 @@ +{"version":3,"names":["TSTypeAnnotation","node","token","space","optional","print","typeAnnotation","TSTypeParameterInstantiation","parent","printList","params","type","length","TSTypeParameter","in","word","out","name","constraint","default","TSParameterProperty","accessibility","readonly","_param","parameter","TSDeclareFunction","declare","_functionHead","TSDeclareMethod","_classMethodHead","TSQualifiedName","left","right","TSCallSignatureDeclaration","tsPrintSignatureDeclarationBase","TSConstructSignatureDeclaration","TSPropertySignature","initializer","tsPrintPropertyOrMethodName","computed","key","TSMethodSignature","kind","TSIndexSignature","static","isStatic","_parameters","parameters","TSAnyKeyword","TSBigIntKeyword","TSUnknownKeyword","TSNumberKeyword","TSObjectKeyword","TSBooleanKeyword","TSStringKeyword","TSSymbolKeyword","TSVoidKeyword","TSUndefinedKeyword","TSNullKeyword","TSNeverKeyword","TSIntrinsicKeyword","TSThisType","TSFunctionType","tsPrintFunctionOrConstructorType","TSConstructorType","abstract","typeParameters","returnType","TSTypeReference","typeName","TSTypePredicate","asserts","parameterName","TSTypeQuery","exprName","TSTypeLiteral","tsPrintTypeLiteralOrInterfaceBody","members","tsPrintBraced","printer","indent","newline","member","dedent","sourceWithOffset","loc","rightBrace","TSArrayType","elementType","TSTupleType","elementTypes","TSOptionalType","TSRestType","TSNamedTupleMember","label","TSUnionType","tsPrintUnionOrIntersectionType","TSIntersectionType","sep","printJoin","types","separator","TSConditionalType","checkType","extendsType","trueType","falseType","TSInferType","typeParameter","TSParenthesizedType","TSTypeOperator","operator","TSIndexedAccessType","objectType","indexType","TSMappedType","nameType","tokenIfPlusMinus","self","tok","TSLiteralType","literal","TSExpressionWithTypeArguments","expression","TSInterfaceDeclaration","id","extends","extendz","body","TSInterfaceBody","TSTypeAliasDeclaration","TSAsExpression","TSTypeAssertion","TSInstantiationExpression","TSEnumDeclaration","const","isConst","TSEnumMember","TSModuleDeclaration","global","TSModuleBlock","TSImportType","argument","qualifier","TSImportEqualsDeclaration","isExport","moduleReference","TSExternalModuleReference","TSNonNullExpression","TSExportAssignment","TSNamespaceExportDeclaration","tsPrintClassMemberModifiers","isField","override"],"sources":["../../src/generators/typescript.ts"],"sourcesContent":["import type Printer from \"../printer\";\nimport type * as t from \"@babel/types\";\n\nexport function TSTypeAnnotation(this: Printer, node: t.TSTypeAnnotation) {\n this.token(\":\");\n this.space();\n // @ts-expect-error todo(flow->ts) can this be removed? `.optional` looks to be not existing property\n if (node.optional) this.token(\"?\");\n this.print(node.typeAnnotation, node);\n}\n\nexport function TSTypeParameterInstantiation(\n this: Printer,\n node: t.TSTypeParameterInstantiation,\n parent: t.Node,\n): void {\n this.token(\"<\");\n this.printList(node.params, node, {});\n if (parent.type === \"ArrowFunctionExpression\" && node.params.length === 1) {\n this.token(\",\");\n }\n this.token(\">\");\n}\n\nexport { TSTypeParameterInstantiation as TSTypeParameterDeclaration };\n\nexport function TSTypeParameter(this: Printer, node: t.TSTypeParameter) {\n if (node.in) {\n this.word(\"in\");\n this.space();\n }\n\n if (node.out) {\n this.word(\"out\");\n this.space();\n }\n\n this.word(\n !process.env.BABEL_8_BREAKING\n ? (node.name as unknown as string)\n : (node.name as unknown as t.Identifier).name,\n );\n\n if (node.constraint) {\n this.space();\n this.word(\"extends\");\n this.space();\n this.print(node.constraint, node);\n }\n\n if (node.default) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.default, node);\n }\n}\n\nexport function TSParameterProperty(\n this: Printer,\n node: t.TSParameterProperty,\n) {\n if (node.accessibility) {\n this.word(node.accessibility);\n this.space();\n }\n\n if (node.readonly) {\n this.word(\"readonly\");\n this.space();\n }\n\n this._param(node.parameter);\n}\n\nexport function TSDeclareFunction(this: Printer, node: t.TSDeclareFunction) {\n if (node.declare) {\n this.word(\"declare\");\n this.space();\n }\n this._functionHead(node);\n this.token(\";\");\n}\n\nexport function TSDeclareMethod(this: Printer, node: t.TSDeclareMethod) {\n this._classMethodHead(node);\n this.token(\";\");\n}\n\nexport function TSQualifiedName(this: Printer, node: t.TSQualifiedName) {\n this.print(node.left, node);\n this.token(\".\");\n this.print(node.right, node);\n}\n\nexport function TSCallSignatureDeclaration(\n this: Printer,\n node: t.TSCallSignatureDeclaration,\n) {\n this.tsPrintSignatureDeclarationBase(node);\n this.token(\";\");\n}\n\nexport function TSConstructSignatureDeclaration(\n this: Printer,\n node: t.TSConstructSignatureDeclaration,\n) {\n this.word(\"new\");\n this.space();\n this.tsPrintSignatureDeclarationBase(node);\n this.token(\";\");\n}\n\nexport function TSPropertySignature(\n this: Printer,\n node: t.TSPropertySignature,\n) {\n const { readonly, initializer } = node;\n if (readonly) {\n this.word(\"readonly\");\n this.space();\n }\n this.tsPrintPropertyOrMethodName(node);\n this.print(node.typeAnnotation, node);\n if (initializer) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(initializer, node);\n }\n this.token(\";\");\n}\n\nexport function tsPrintPropertyOrMethodName(\n this: Printer,\n node: t.TSPropertySignature | t.TSMethodSignature,\n) {\n if (node.computed) {\n this.token(\"[\");\n }\n this.print(node.key, node);\n if (node.computed) {\n this.token(\"]\");\n }\n if (node.optional) {\n this.token(\"?\");\n }\n}\n\nexport function TSMethodSignature(this: Printer, node: t.TSMethodSignature) {\n const { kind } = node;\n if (kind === \"set\" || kind === \"get\") {\n this.word(kind);\n this.space();\n }\n this.tsPrintPropertyOrMethodName(node);\n this.tsPrintSignatureDeclarationBase(node);\n this.token(\";\");\n}\n\nexport function TSIndexSignature(this: Printer, node: t.TSIndexSignature) {\n const { readonly, static: isStatic } = node;\n if (isStatic) {\n this.word(\"static\");\n this.space();\n }\n if (readonly) {\n this.word(\"readonly\");\n this.space();\n }\n this.token(\"[\");\n this._parameters(node.parameters, node);\n this.token(\"]\");\n this.print(node.typeAnnotation, node);\n this.token(\";\");\n}\n\nexport function TSAnyKeyword(this: Printer) {\n this.word(\"any\");\n}\nexport function TSBigIntKeyword(this: Printer) {\n this.word(\"bigint\");\n}\nexport function TSUnknownKeyword(this: Printer) {\n this.word(\"unknown\");\n}\nexport function TSNumberKeyword(this: Printer) {\n this.word(\"number\");\n}\nexport function TSObjectKeyword(this: Printer) {\n this.word(\"object\");\n}\nexport function TSBooleanKeyword(this: Printer) {\n this.word(\"boolean\");\n}\nexport function TSStringKeyword(this: Printer) {\n this.word(\"string\");\n}\nexport function TSSymbolKeyword(this: Printer) {\n this.word(\"symbol\");\n}\nexport function TSVoidKeyword(this: Printer) {\n this.word(\"void\");\n}\nexport function TSUndefinedKeyword(this: Printer) {\n this.word(\"undefined\");\n}\nexport function TSNullKeyword(this: Printer) {\n this.word(\"null\");\n}\nexport function TSNeverKeyword(this: Printer) {\n this.word(\"never\");\n}\nexport function TSIntrinsicKeyword(this: Printer) {\n this.word(\"intrinsic\");\n}\n\nexport function TSThisType(this: Printer) {\n this.word(\"this\");\n}\n\nexport function TSFunctionType(this: Printer, node: t.TSFunctionType) {\n this.tsPrintFunctionOrConstructorType(node);\n}\n\nexport function TSConstructorType(this: Printer, node: t.TSConstructorType) {\n if (node.abstract) {\n this.word(\"abstract\");\n this.space();\n }\n this.word(\"new\");\n this.space();\n this.tsPrintFunctionOrConstructorType(node);\n}\n\nexport function tsPrintFunctionOrConstructorType(\n this: Printer,\n node: t.TSFunctionType | t.TSConstructorType,\n) {\n const { typeParameters } = node;\n const parameters = process.env.BABEL_8_BREAKING\n ? // @ts-ignore(Babel 7 vs Babel 8) Babel 8 AST shape\n node.params\n : // @ts-ignore(Babel 7 vs Babel 8) Babel 7 AST shape\n node.parameters;\n this.print(typeParameters, node);\n this.token(\"(\");\n this._parameters(parameters, node);\n this.token(\")\");\n this.space();\n this.token(\"=>\");\n this.space();\n const returnType = process.env.BABEL_8_BREAKING\n ? // @ts-ignore(Babel 7 vs Babel 8) Babel 8 AST shape\n node.returnType\n : // @ts-ignore(Babel 7 vs Babel 8) Babel 7 AST shape\n node.typeAnnotation;\n this.print(returnType.typeAnnotation, node);\n}\n\nexport function TSTypeReference(this: Printer, node: t.TSTypeReference) {\n this.print(node.typeName, node, true);\n this.print(node.typeParameters, node, true);\n}\n\nexport function TSTypePredicate(this: Printer, node: t.TSTypePredicate) {\n if (node.asserts) {\n this.word(\"asserts\");\n this.space();\n }\n this.print(node.parameterName);\n if (node.typeAnnotation) {\n this.space();\n this.word(\"is\");\n this.space();\n this.print(node.typeAnnotation.typeAnnotation);\n }\n}\n\nexport function TSTypeQuery(this: Printer, node: t.TSTypeQuery) {\n this.word(\"typeof\");\n this.space();\n this.print(node.exprName);\n\n if (node.typeParameters) {\n this.print(node.typeParameters, node);\n }\n}\n\nexport function TSTypeLiteral(this: Printer, node: t.TSTypeLiteral) {\n this.tsPrintTypeLiteralOrInterfaceBody(node.members, node);\n}\n\nexport function tsPrintTypeLiteralOrInterfaceBody(\n this: Printer,\n members: t.TSTypeElement[],\n node: t.TSType | t.TSInterfaceBody,\n) {\n tsPrintBraced(this, members, node);\n}\n\nfunction tsPrintBraced(printer: Printer, members: t.Node[], node: t.Node) {\n printer.token(\"{\");\n if (members.length) {\n printer.indent();\n printer.newline();\n for (const member of members) {\n printer.print(member, node);\n //this.token(sep);\n printer.newline();\n }\n printer.dedent();\n }\n\n printer.sourceWithOffset(\"end\", node.loc, 0, -1);\n\n printer.rightBrace();\n}\n\nexport function TSArrayType(this: Printer, node: t.TSArrayType) {\n this.print(node.elementType, node, true);\n\n this.token(\"[]\");\n}\n\nexport function TSTupleType(this: Printer, node: t.TSTupleType) {\n this.token(\"[\");\n this.printList(node.elementTypes, node);\n this.token(\"]\");\n}\n\nexport function TSOptionalType(this: Printer, node: t.TSOptionalType) {\n this.print(node.typeAnnotation, node);\n this.token(\"?\");\n}\n\nexport function TSRestType(this: Printer, node: t.TSRestType) {\n this.token(\"...\");\n this.print(node.typeAnnotation, node);\n}\n\nexport function TSNamedTupleMember(this: Printer, node: t.TSNamedTupleMember) {\n this.print(node.label, node);\n if (node.optional) this.token(\"?\");\n this.token(\":\");\n this.space();\n this.print(node.elementType, node);\n}\n\nexport function TSUnionType(this: Printer, node: t.TSUnionType) {\n tsPrintUnionOrIntersectionType(this, node, \"|\");\n}\n\nexport function TSIntersectionType(this: Printer, node: t.TSIntersectionType) {\n tsPrintUnionOrIntersectionType(this, node, \"&\");\n}\n\nfunction tsPrintUnionOrIntersectionType(\n printer: Printer,\n node: t.TSUnionType | t.TSIntersectionType,\n sep: \"|\" | \"&\",\n) {\n printer.printJoin(node.types, node, {\n separator() {\n this.space();\n this.token(sep);\n this.space();\n },\n });\n}\n\nexport function TSConditionalType(this: Printer, node: t.TSConditionalType) {\n this.print(node.checkType);\n this.space();\n this.word(\"extends\");\n this.space();\n this.print(node.extendsType);\n this.space();\n this.token(\"?\");\n this.space();\n this.print(node.trueType);\n this.space();\n this.token(\":\");\n this.space();\n this.print(node.falseType);\n}\n\nexport function TSInferType(this: Printer, node: t.TSInferType) {\n this.token(\"infer\");\n this.space();\n this.print(node.typeParameter);\n}\n\nexport function TSParenthesizedType(\n this: Printer,\n node: t.TSParenthesizedType,\n) {\n this.token(\"(\");\n this.print(node.typeAnnotation, node);\n this.token(\")\");\n}\n\nexport function TSTypeOperator(this: Printer, node: t.TSTypeOperator) {\n this.word(node.operator);\n this.space();\n this.print(node.typeAnnotation, node);\n}\n\nexport function TSIndexedAccessType(\n this: Printer,\n node: t.TSIndexedAccessType,\n) {\n this.print(node.objectType, node, true);\n this.token(\"[\");\n this.print(node.indexType, node);\n this.token(\"]\");\n}\n\nexport function TSMappedType(this: Printer, node: t.TSMappedType) {\n const { nameType, optional, readonly, typeParameter } = node;\n this.token(\"{\");\n this.space();\n if (readonly) {\n tokenIfPlusMinus(this, readonly);\n this.word(\"readonly\");\n this.space();\n }\n\n this.token(\"[\");\n this.word(\n !process.env.BABEL_8_BREAKING\n ? (typeParameter.name as unknown as string)\n : (typeParameter.name as unknown as t.Identifier).name,\n );\n this.space();\n this.word(\"in\");\n this.space();\n this.print(typeParameter.constraint, typeParameter);\n\n if (nameType) {\n this.space();\n this.word(\"as\");\n this.space();\n this.print(nameType, node);\n }\n\n this.token(\"]\");\n\n if (optional) {\n tokenIfPlusMinus(this, optional);\n this.token(\"?\");\n }\n this.token(\":\");\n this.space();\n this.print(node.typeAnnotation, node);\n this.space();\n this.token(\"}\");\n}\n\nfunction tokenIfPlusMinus(self: Printer, tok: true | \"+\" | \"-\") {\n if (tok !== true) {\n self.token(tok);\n }\n}\n\nexport function TSLiteralType(this: Printer, node: t.TSLiteralType) {\n this.print(node.literal, node);\n}\n\nexport function TSExpressionWithTypeArguments(\n this: Printer,\n node: t.TSExpressionWithTypeArguments,\n) {\n this.print(node.expression, node);\n this.print(node.typeParameters, node);\n}\n\nexport function TSInterfaceDeclaration(\n this: Printer,\n node: t.TSInterfaceDeclaration,\n) {\n const { declare, id, typeParameters, extends: extendz, body } = node;\n if (declare) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"interface\");\n this.space();\n this.print(id, node);\n this.print(typeParameters, node);\n if (extendz?.length) {\n this.space();\n this.word(\"extends\");\n this.space();\n this.printList(extendz, node);\n }\n this.space();\n this.print(body, node);\n}\n\nexport function TSInterfaceBody(this: Printer, node: t.TSInterfaceBody) {\n this.tsPrintTypeLiteralOrInterfaceBody(node.body, node);\n}\n\nexport function TSTypeAliasDeclaration(\n this: Printer,\n node: t.TSTypeAliasDeclaration,\n) {\n const { declare, id, typeParameters, typeAnnotation } = node;\n if (declare) {\n this.word(\"declare\");\n this.space();\n }\n this.word(\"type\");\n this.space();\n this.print(id, node);\n this.print(typeParameters, node);\n this.space();\n this.token(\"=\");\n this.space();\n this.print(typeAnnotation, node);\n this.token(\";\");\n}\n\nexport function TSAsExpression(this: Printer, node: t.TSAsExpression) {\n const { expression, typeAnnotation } = node;\n this.print(expression, node);\n this.space();\n this.word(\"as\");\n this.space();\n this.print(typeAnnotation, node);\n}\n\nexport function TSTypeAssertion(this: Printer, node: t.TSTypeAssertion) {\n const { typeAnnotation, expression } = node;\n this.token(\"<\");\n this.print(typeAnnotation, node);\n this.token(\">\");\n this.space();\n this.print(expression, node);\n}\n\nexport function TSInstantiationExpression(\n this: Printer,\n node: t.TSInstantiationExpression,\n) {\n this.print(node.expression, node);\n this.print(node.typeParameters, node);\n}\n\nexport function TSEnumDeclaration(this: Printer, node: t.TSEnumDeclaration) {\n const { declare, const: isConst, id, members } = node;\n if (declare) {\n this.word(\"declare\");\n this.space();\n }\n if (isConst) {\n this.word(\"const\");\n this.space();\n }\n this.word(\"enum\");\n this.space();\n this.print(id, node);\n this.space();\n tsPrintBraced(this, members, node);\n}\n\nexport function TSEnumMember(this: Printer, node: t.TSEnumMember) {\n const { id, initializer } = node;\n this.print(id, node);\n if (initializer) {\n this.space();\n this.token(\"=\");\n this.space();\n this.print(initializer, node);\n }\n this.token(\",\");\n}\n\nexport function TSModuleDeclaration(\n this: Printer,\n node: t.TSModuleDeclaration,\n) {\n const { declare, id } = node;\n\n if (declare) {\n this.word(\"declare\");\n this.space();\n }\n\n if (!node.global) {\n this.word(id.type === \"Identifier\" ? \"namespace\" : \"module\");\n this.space();\n }\n this.print(id, node);\n\n if (!node.body) {\n this.token(\";\");\n return;\n }\n\n let body = node.body;\n while (body.type === \"TSModuleDeclaration\") {\n this.token(\".\");\n this.print(body.id, body);\n body = body.body;\n }\n\n this.space();\n this.print(body, node);\n}\n\nexport function TSModuleBlock(this: Printer, node: t.TSModuleBlock) {\n tsPrintBraced(this, node.body, node);\n}\n\nexport function TSImportType(this: Printer, node: t.TSImportType) {\n const { argument, qualifier, typeParameters } = node;\n this.word(\"import\");\n this.token(\"(\");\n this.print(argument, node);\n this.token(\")\");\n if (qualifier) {\n this.token(\".\");\n this.print(qualifier, node);\n }\n if (typeParameters) {\n this.print(typeParameters, node);\n }\n}\n\nexport function TSImportEqualsDeclaration(\n this: Printer,\n node: t.TSImportEqualsDeclaration,\n) {\n const { isExport, id, moduleReference } = node;\n if (isExport) {\n this.word(\"export\");\n this.space();\n }\n this.word(\"import\");\n this.space();\n this.print(id, node);\n this.space();\n this.token(\"=\");\n this.space();\n this.print(moduleReference, node);\n this.token(\";\");\n}\n\nexport function TSExternalModuleReference(\n this: Printer,\n node: t.TSExternalModuleReference,\n) {\n this.token(\"require(\");\n this.print(node.expression, node);\n this.token(\")\");\n}\n\nexport function TSNonNullExpression(\n this: Printer,\n node: t.TSNonNullExpression,\n) {\n this.print(node.expression, node);\n this.token(\"!\");\n}\n\nexport function TSExportAssignment(this: Printer, node: t.TSExportAssignment) {\n this.word(\"export\");\n this.space();\n this.token(\"=\");\n this.space();\n this.print(node.expression, node);\n this.token(\";\");\n}\n\nexport function TSNamespaceExportDeclaration(\n this: Printer,\n node: t.TSNamespaceExportDeclaration,\n) {\n this.word(\"export\");\n this.space();\n this.word(\"as\");\n this.space();\n this.word(\"namespace\");\n this.space();\n this.print(node.id, node);\n}\n\nexport function tsPrintSignatureDeclarationBase(this: Printer, node: any) {\n const { typeParameters } = node;\n const parameters = process.env.BABEL_8_BREAKING\n ? node.params\n : node.parameters;\n this.print(typeParameters, node);\n this.token(\"(\");\n this._parameters(parameters, node);\n this.token(\")\");\n const returnType = process.env.BABEL_8_BREAKING\n ? node.returnType\n : node.typeAnnotation;\n this.print(returnType, node);\n}\n\nexport function tsPrintClassMemberModifiers(\n this: Printer,\n node:\n | t.ClassProperty\n | t.ClassAccessorProperty\n | t.ClassMethod\n | t.ClassPrivateMethod\n | t.TSDeclareMethod,\n) {\n const isField =\n node.type === \"ClassAccessorProperty\" || node.type === \"ClassProperty\";\n if (isField && node.declare) {\n this.word(\"declare\");\n this.space();\n }\n if (node.accessibility) {\n this.word(node.accessibility);\n this.space();\n }\n if (node.static) {\n this.word(\"static\");\n this.space();\n }\n if (node.override) {\n this.word(\"override\");\n this.space();\n }\n if (node.abstract) {\n this.word(\"abstract\");\n this.space();\n }\n if (isField && node.readonly) {\n this.word(\"readonly\");\n this.space();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,SAASA,gBAAT,CAAyCC,IAAzC,EAAmE;EACxE,KAAKC,SAAL;EACA,KAAKC,KAAL;EAEA,IAAIF,IAAI,CAACG,QAAT,EAAmB,KAAKF,SAAL;EACnB,KAAKG,KAAL,CAAWJ,IAAI,CAACK,cAAhB,EAAgCL,IAAhC;AACD;;AAEM,SAASM,4BAAT,CAELN,IAFK,EAGLO,MAHK,EAIC;EACN,KAAKN,SAAL;EACA,KAAKO,SAAL,CAAeR,IAAI,CAACS,MAApB,EAA4BT,IAA5B,EAAkC,EAAlC;;EACA,IAAIO,MAAM,CAACG,IAAP,KAAgB,yBAAhB,IAA6CV,IAAI,CAACS,MAAL,CAAYE,MAAZ,KAAuB,CAAxE,EAA2E;IACzE,KAAKV,SAAL;EACD;;EACD,KAAKA,SAAL;AACD;;AAIM,SAASW,eAAT,CAAwCZ,IAAxC,EAAiE;EACtE,IAAIA,IAAI,CAACa,EAAT,EAAa;IACX,KAAKC,IAAL,CAAU,IAAV;IACA,KAAKZ,KAAL;EACD;;EAED,IAAIF,IAAI,CAACe,GAAT,EAAc;IACZ,KAAKD,IAAL,CAAU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KAAL;EACD;;EACD,IAAIF,IAAI,CAACoB,aAAT,EAAwB;IACtB,KAAKN,IAAL,CAAUd,IAAI,CAACoB,aAAf;IACA,KAAKlB,KAAL;EACD;;EACD,IAAIF,IAAI,CAAC2C,MAAT,EAAiB;IACf,KAAK7B,IAAL,CAAU,QAAV;IACA,KAAKZ,KAAL;EACD;;EACD,IAAIF,IAAI,CAACwJ,QAAT,EAAmB;IACjB,KAAK1I,IAAL,CAAU,UAAV;IACA,KAAKZ,KAAL;EACD;;EACD,IAAIF,IAAI,CAACgE,QAAT,EAAmB;IACjB,KAAKlD,IAAL,CAAU,UAAV;IACA,KAAKZ,KAAL;EACD;;EACD,IAAIqJ,OAAO,IAAIvJ,IAAI,CAACqB,QAApB,EAA8B;IAC5B,KAAKP,IAAL,CAAU,UAAV;IACA,KAAKZ,KAAL;EACD;AACF"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/index.js b/node_modules/@babel/generator/lib/index.js new file mode 100644 index 0000000..fea3370 --- /dev/null +++ b/node_modules/@babel/generator/lib/index.js @@ -0,0 +1,98 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CodeGenerator = void 0; +exports.default = generate; + +var _sourceMap = require("./source-map"); + +var _printer = require("./printer"); + +class Generator extends _printer.default { + constructor(ast, opts = {}, code) { + const format = normalizeOptions(code, opts); + const map = opts.sourceMaps ? new _sourceMap.default(opts, code) : null; + super(format, map); + this.ast = void 0; + this.ast = ast; + } + + generate() { + return super.generate(this.ast); + } + +} + +function normalizeOptions(code, opts) { + const format = { + auxiliaryCommentBefore: opts.auxiliaryCommentBefore, + auxiliaryCommentAfter: opts.auxiliaryCommentAfter, + shouldPrintComment: opts.shouldPrintComment, + retainLines: opts.retainLines, + retainFunctionParens: opts.retainFunctionParens, + comments: opts.comments == null || opts.comments, + compact: opts.compact, + minified: opts.minified, + concise: opts.concise, + indent: { + adjustMultilineComment: true, + style: " " + }, + jsescOption: Object.assign({ + quotes: "double", + wrap: true, + minimal: false + }, opts.jsescOption), + recordAndTupleSyntaxType: opts.recordAndTupleSyntaxType, + topicToken: opts.topicToken + }; + { + format.decoratorsBeforeExport = !!opts.decoratorsBeforeExport; + format.jsonCompatibleStrings = opts.jsonCompatibleStrings; + } + + if (format.minified) { + format.compact = true; + + format.shouldPrintComment = format.shouldPrintComment || (() => format.comments); + } else { + format.shouldPrintComment = format.shouldPrintComment || (value => format.comments || value.includes("@license") || value.includes("@preserve")); + } + + if (format.compact === "auto") { + format.compact = code.length > 500000; + + if (format.compact) { + console.error("[BABEL] Note: The code generator has deoptimised the styling of " + `${opts.filename} as it exceeds the max of ${"500KB"}.`); + } + } + + if (format.compact) { + format.indent.adjustMultilineComment = false; + } + + return format; +} + +class CodeGenerator { + constructor(ast, opts, code) { + this._generator = void 0; + this._generator = new Generator(ast, opts, code); + } + + generate() { + return this._generator.generate(); + } + +} + +exports.CodeGenerator = CodeGenerator; + +function generate(ast, opts, code) { + const gen = new Generator(ast, opts, code); + return gen.generate(); +} + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/generator/lib/index.js.map b/node_modules/@babel/generator/lib/index.js.map new file mode 100644 index 0000000..07e2b3f --- /dev/null +++ b/node_modules/@babel/generator/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["Generator","Printer","constructor","ast","opts","code","format","normalizeOptions","map","sourceMaps","SourceMap","generate","auxiliaryCommentBefore","auxiliaryCommentAfter","shouldPrintComment","retainLines","retainFunctionParens","comments","compact","minified","concise","indent","adjustMultilineComment","style","jsescOption","quotes","wrap","minimal","recordAndTupleSyntaxType","topicToken","decoratorsBeforeExport","jsonCompatibleStrings","value","includes","length","console","error","filename","CodeGenerator","_generator","gen"],"sources":["../src/index.ts"],"sourcesContent":["import SourceMap from \"./source-map\";\nimport Printer from \"./printer\";\nimport type * as t from \"@babel/types\";\nimport type { Opts as jsescOptions } from \"jsesc\";\nimport type { Format } from \"./printer\";\nimport type {\n RecordAndTuplePluginOptions,\n PipelineOperatorPluginOptions,\n} from \"@babel/parser\";\nimport type { DecodedSourceMap, Mapping } from \"@jridgewell/gen-mapping\";\n\n/**\n * Babel's code generator, turns an ast into code, maintaining sourcemaps,\n * user preferences, and valid output.\n */\n\nclass Generator extends Printer {\n constructor(\n ast: t.Node,\n opts: GeneratorOptions = {},\n code: string | { [filename: string]: string },\n ) {\n const format = normalizeOptions(code, opts);\n const map = opts.sourceMaps ? new SourceMap(opts, code) : null;\n super(format, map);\n\n this.ast = ast;\n }\n\n ast: t.Node;\n\n /**\n * Generate code and sourcemap from ast.\n *\n * Appends comments that weren't attached to any node to the end of the generated output.\n */\n\n generate() {\n return super.generate(this.ast);\n }\n}\n\n/**\n * Normalize generator options, setting defaults.\n *\n * - Detects code indentation.\n * - If `opts.compact = \"auto\"` and the code is over 500KB, `compact` will be set to `true`.\n */\n\nfunction normalizeOptions(\n code: string | { [filename: string]: string },\n opts: GeneratorOptions,\n): Format {\n const format: Format = {\n auxiliaryCommentBefore: opts.auxiliaryCommentBefore,\n auxiliaryCommentAfter: opts.auxiliaryCommentAfter,\n shouldPrintComment: opts.shouldPrintComment,\n retainLines: opts.retainLines,\n retainFunctionParens: opts.retainFunctionParens,\n comments: opts.comments == null || opts.comments,\n compact: opts.compact,\n minified: opts.minified,\n concise: opts.concise,\n indent: {\n adjustMultilineComment: true,\n style: \" \",\n },\n jsescOption: {\n quotes: \"double\",\n wrap: true,\n minimal: process.env.BABEL_8_BREAKING ? true : false,\n ...opts.jsescOption,\n },\n recordAndTupleSyntaxType: opts.recordAndTupleSyntaxType,\n topicToken: opts.topicToken,\n };\n\n if (!process.env.BABEL_8_BREAKING) {\n format.decoratorsBeforeExport = !!opts.decoratorsBeforeExport;\n format.jsonCompatibleStrings = opts.jsonCompatibleStrings;\n }\n\n if (format.minified) {\n format.compact = true;\n\n format.shouldPrintComment =\n format.shouldPrintComment || (() => format.comments);\n } else {\n format.shouldPrintComment =\n format.shouldPrintComment ||\n (value =>\n format.comments ||\n value.includes(\"@license\") ||\n value.includes(\"@preserve\"));\n }\n\n if (format.compact === \"auto\") {\n format.compact = code.length > 500_000; // 500KB\n\n if (format.compact) {\n console.error(\n \"[BABEL] Note: The code generator has deoptimised the styling of \" +\n `${opts.filename} as it exceeds the max of ${\"500KB\"}.`,\n );\n }\n }\n\n if (format.compact) {\n format.indent.adjustMultilineComment = false;\n }\n\n return format;\n}\n\nexport interface GeneratorOptions {\n /**\n * Optional string to add as a block comment at the start of the output file.\n */\n auxiliaryCommentBefore?: string;\n\n /**\n * Optional string to add as a block comment at the end of the output file.\n */\n auxiliaryCommentAfter?: string;\n\n /**\n * Function that takes a comment (as a string) and returns true if the comment should be included in the output.\n * By default, comments are included if `opts.comments` is `true` or if `opts.minifed` is `false` and the comment\n * contains `@preserve` or `@license`.\n */\n shouldPrintComment?(comment: string): boolean;\n\n /**\n * Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces).\n * Defaults to `false`.\n */\n retainLines?: boolean;\n\n /**\n * Retain parens around function expressions (could be used to change engine parsing behavior)\n * Defaults to `false`.\n */\n retainFunctionParens?: boolean;\n\n /**\n * Should comments be included in output? Defaults to `true`.\n */\n comments?: boolean;\n\n /**\n * Set to true to avoid adding whitespace for formatting. Defaults to the value of `opts.minified`.\n */\n compact?: boolean | \"auto\";\n\n /**\n * Should the output be minified. Defaults to `false`.\n */\n minified?: boolean;\n\n /**\n * Set to true to reduce whitespace (but not as much as opts.compact). Defaults to `false`.\n */\n concise?: boolean;\n\n /**\n * Used in warning messages\n */\n filename?: string;\n\n /**\n * Enable generating source maps. Defaults to `false`.\n */\n sourceMaps?: boolean;\n\n /**\n * A root for all relative URLs in the source map.\n */\n sourceRoot?: string;\n\n /**\n * The filename for the source code (i.e. the code in the `code` argument).\n * This will only be used if `code` is a string.\n */\n sourceFileName?: string;\n\n /**\n * Set to true to run jsesc with \"json\": true to print \"\\u00A9\" vs. \"©\";\n * @deprecated use `jsescOptions: { json: true }` instead\n */\n jsonCompatibleStrings?: boolean;\n\n /**\n * Set to true to enable support for experimental decorators syntax before module exports.\n * Defaults to `false`.\n * @deprecated Removed in Babel 8\n */\n decoratorsBeforeExport?: boolean;\n\n /**\n * Options for outputting jsesc representation.\n */\n jsescOption?: jsescOptions;\n\n /**\n * For use with the recordAndTuple token.\n */\n recordAndTupleSyntaxType?: RecordAndTuplePluginOptions[\"syntaxType\"];\n /**\n * For use with the Hack-style pipe operator.\n * Changes what token is used for pipe bodies’ topic references.\n */\n topicToken?: PipelineOperatorPluginOptions[\"topicToken\"];\n}\n\nexport interface GeneratorResult {\n code: string;\n map: {\n version: number;\n sources: readonly string[];\n names: readonly string[];\n sourceRoot?: string;\n sourcesContent?: readonly string[];\n mappings: string;\n file?: string;\n } | null;\n decodedMap: DecodedSourceMap | undefined;\n rawMappings: Mapping[] | undefined;\n}\n\n/**\n * We originally exported the Generator class above, but to make it extra clear that it is a private API,\n * we have moved that to an internal class instance and simplified the interface to the two public methods\n * that we wish to support.\n */\n\nexport class CodeGenerator {\n private _generator: Generator;\n constructor(ast: t.Node, opts?: GeneratorOptions, code?: string) {\n this._generator = new Generator(ast, opts, code);\n }\n generate(): GeneratorResult {\n return this._generator.generate();\n }\n}\n\n/**\n * Turns an AST into code, maintaining sourcemaps, user preferences, and valid output.\n * @param ast - the abstract syntax tree from which to generate output code.\n * @param opts - used for specifying options for code generation.\n * @param code - the original source code, used for source maps.\n * @returns - an object containing the output code and source map.\n */\nexport default function generate(\n ast: t.Node,\n opts?: GeneratorOptions,\n code?: string | { [filename: string]: string },\n) {\n const gen = new Generator(ast, opts, code);\n return gen.generate();\n}\n"],"mappings":";;;;;;;;AAAA;;AACA;;AAeA,MAAMA,SAAN,SAAwBC,gBAAxB,CAAgC;EAC9BC,WAAW,CACTC,GADS,EAETC,IAAsB,GAAG,EAFhB,EAGTC,IAHS,EAIT;IACA,MAAMC,MAAM,GAAGC,gBAAgB,CAACF,IAAD,EAAOD,IAAP,CAA/B;IACA,MAAMI,GAAG,GAAGJ,IAAI,CAAC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/node_modules/@babel/generator/lib/node/index.js b/node_modules/@babel/generator/lib/node/index.js new file mode 100644 index 0000000..07dc2f0 --- /dev/null +++ b/node_modules/@babel/generator/lib/node/index.js @@ -0,0 +1,101 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.needsParens = needsParens; +exports.needsWhitespace = needsWhitespace; +exports.needsWhitespaceAfter = needsWhitespaceAfter; +exports.needsWhitespaceBefore = needsWhitespaceBefore; + +var whitespace = require("./whitespace"); + +var parens = require("./parentheses"); + +var _t = require("@babel/types"); + +const { + FLIPPED_ALIAS_KEYS, + isCallExpression, + isExpressionStatement, + isMemberExpression, + isNewExpression +} = _t; + +function expandAliases(obj) { + const newObj = {}; + + function add(type, func) { + const fn = newObj[type]; + newObj[type] = fn ? function (node, parent, stack) { + const result = fn(node, parent, stack); + return result == null ? func(node, parent, stack) : result; + } : func; + } + + for (const type of Object.keys(obj)) { + const aliases = FLIPPED_ALIAS_KEYS[type]; + + if (aliases) { + for (const alias of aliases) { + add(alias, obj[type]); + } + } else { + add(type, obj[type]); + } + } + + return newObj; +} + +const expandedParens = expandAliases(parens); +const expandedWhitespaceNodes = expandAliases(whitespace.nodes); + +function find(obj, node, parent, printStack) { + const fn = obj[node.type]; + return fn ? fn(node, parent, printStack) : null; +} + +function isOrHasCallExpression(node) { + if (isCallExpression(node)) { + return true; + } + + return isMemberExpression(node) && isOrHasCallExpression(node.object); +} + +function needsWhitespace(node, parent, type) { + if (!node) return false; + + if (isExpressionStatement(node)) { + node = node.expression; + } + + const flag = find(expandedWhitespaceNodes, node, parent); + + if (typeof flag === "number") { + return (flag & type) !== 0; + } + + return false; +} + +function needsWhitespaceBefore(node, parent) { + return needsWhitespace(node, parent, 1); +} + +function needsWhitespaceAfter(node, parent) { + return needsWhitespace(node, parent, 2); +} + +function needsParens(node, parent, printStack) { + if (!parent) return false; + + if (isNewExpression(parent) && parent.callee === node) { + if (isOrHasCallExpression(node)) return true; + } + + return find(expandedParens, node, parent, printStack); +} + +//# sourceMappingURL=index.js.map diff --git a/node_modules/@babel/generator/lib/node/index.js.map b/node_modules/@babel/generator/lib/node/index.js.map new file mode 100644 index 0000000..687e385 --- /dev/null +++ b/node_modules/@babel/generator/lib/node/index.js.map @@ -0,0 +1 @@ +{"version":3,"names":["FLIPPED_ALIAS_KEYS","isCallExpression","isExpressionStatement","isMemberExpression","isNewExpression","expandAliases","obj","newObj","add","type","func","fn","node","parent","stack","result","Object","keys","aliases","alias","expandedParens","parens","expandedWhitespaceNodes","whitespace","nodes","find","printStack","isOrHasCallExpression","object","needsWhitespace","expression","flag","needsWhitespaceBefore","needsWhitespaceAfter","needsParens","callee"],"sources":["../../src/node/index.ts"],"sourcesContent":["import * as whitespace from \"./whitespace\";\nimport * as parens from \"./parentheses\";\nimport {\n FLIPPED_ALIAS_KEYS,\n isCallExpression,\n isExpressionStatement,\n isMemberExpression,\n isNewExpression,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\n\nimport type { WhitespaceFlag } from \"./whitespace\";\n\nexport type NodeHandlers = {\n [K in string]?: (\n node: K extends t.Node[\"type\"] ? Extract : t.Node,\n // todo:\n // node: K extends keyof typeof t\n // ? Extract\n // : t.Node,\n parent: t.Node,\n stack: t.Node[],\n ) => R;\n};\n\nfunction expandAliases(obj: NodeHandlers) {\n const newObj: NodeHandlers = {};\n\n function add(\n type: string,\n func: (node: t.Node, parent: t.Node, stack: t.Node[]) => R,\n ) {\n const fn = newObj[type];\n newObj[type] = fn\n ? function (node, parent, stack) {\n const result = fn(node, parent, stack);\n\n return result == null ? func(node, parent, stack) : result;\n }\n : func;\n }\n\n for (const type of Object.keys(obj)) {\n const aliases = FLIPPED_ALIAS_KEYS[type];\n if (aliases) {\n for (const alias of aliases) {\n add(alias, obj[type]);\n }\n } else {\n add(type, obj[type]);\n }\n }\n\n return newObj;\n}\n\n// Rather than using `t.is` on each object property, we pre-expand any type aliases\n// into concrete types so that the 'find' call below can be as fast as possible.\nconst expandedParens = expandAliases(parens);\nconst expandedWhitespaceNodes = expandAliases(whitespace.nodes);\n\nfunction find(\n obj: NodeHandlers,\n node: t.Node,\n parent: t.Node,\n printStack?: t.Node[],\n): R | null {\n const fn = obj[node.type];\n return fn ? fn(node, parent, printStack) : null;\n}\n\nfunction isOrHasCallExpression(node: t.Node): boolean {\n if (isCallExpression(node)) {\n return true;\n }\n\n return isMemberExpression(node) && isOrHasCallExpression(node.object);\n}\n\nexport function needsWhitespace(\n node: t.Node,\n parent: t.Node,\n type: WhitespaceFlag,\n): boolean {\n if (!node) return false;\n\n if (isExpressionStatement(node)) {\n node = node.expression;\n }\n\n const flag = find(expandedWhitespaceNodes, node, parent);\n\n if (typeof flag === \"number\") {\n return (flag & type) !== 0;\n }\n\n return false;\n}\n\nexport function needsWhitespaceBefore(node: t.Node, parent: t.Node) {\n return needsWhitespace(node, parent, 1);\n}\n\nexport function needsWhitespaceAfter(node: t.Node, parent: t.Node) {\n return needsWhitespace(node, parent, 2);\n}\n\nexport function needsParens(\n node: t.Node,\n parent: t.Node,\n printStack?: t.Node[],\n) {\n if (!parent) return false;\n\n if (isNewExpression(parent) && parent.callee === node) {\n if (isOrHasCallExpression(node)) return true;\n }\n\n return find(expandedParens, node, parent, printStack);\n}\n"],"mappings":";;;;;;;;;;AAAA;;AACA;;AACA;;;EACEA,kB;EACAC,gB;EACAC,qB;EACAC,kB;EACAC;;;AAkBF,SAASC,aAAT,CAA0BC,GAA1B,EAAgD;EAC9C,MAAMC,MAAuB,GAAG,EAAhC;;EAEA,SAASC,GAAT,CACEC,IADF,EAEEC,IAFF,EAGE;IACA,MAAMC,EAAE,GAAGJ,MAAM,CAACE,IAAD,CAAjB;IACAF,MAAM,CAACE,IAAD,CAAN,GAAeE,EAAE,GACb,UAAUC,IAAV,EAAgBC,MAAhB,EAAwBC,KAAxB,EAA+B;MAC7B,MAAMC,MAAM,GAAGJ,EAAE,CAACC,IAAD,EAAOC,MAAP,EAAeC,KAAf,CAAjB;MAEA,OAAOC,MA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AI,GAAGA,IAAI,CAACkB,UAAZ;EACD;;EAED,MAAMC,IAAI,GAAGN,IAAI,CAACH,uBAAD,EAA0BV,IAA1B,EAAgCC,MAAhC,CAAjB;;EAEA,IAAI,OAAOkB,IAAP,KAAgB,QAApB,EAA8B;IAC5B,OAAO,CAACA,IAAI,GAAGtB,IAAR,MAAkB,CAAzB;EACD;;EAED,OAAO,KAAP;AACD;;AAEM,SAASuB,qBAAT,CAA+BpB,IAA/B,EAA6CC,MAA7C,EAA6D;EAClE,OAAOgB,eAAe,CAACjB,IAAD,EAAOC,MAAP,EAAe,CAAf,CAAtB;AACD;;AAEM,SAASoB,oBAAT,CAA8BrB,IAA9B,EAA4CC,MAA5C,EAA4D;EACjE,OAAOgB,eAAe,CAACjB,IAAD,EAAOC,MAAP,EAAe,CAAf,CAAtB;AACD;;AAEM,SAASqB,WAAT,CACLtB,IADK,EAELC,MAFK,EAGLa,UAHK,EAIL;EACA,IAAI,CAACb,MAAL,EAAa,OAAO,KAAP;;EAEb,IAAIT,eAAe,CAACS,MAAD,CAAf,IAA2BA,MAAM,CAACsB,MAAP,KAAkBvB,IAAjD,EAAuD;IACrD,IAAIe,qBAAqB,CAACf,IAAD,CAAzB,EAAiC,OAAO,IAAP;EAClC;;EAED,OAAOa,IAAI,CAACL,cAAD,EAAiBR,IAAjB,EAAuBC,MAAvB,EAA+Ba,UAA/B,CAAX;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/node/parentheses.js b/node_modules/@babel/generator/lib/node/parentheses.js new file mode 100644 index 0000000..616797a --- /dev/null +++ b/node_modules/@babel/generator/lib/node/parentheses.js @@ -0,0 +1,348 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ArrowFunctionExpression = ArrowFunctionExpression; +exports.AssignmentExpression = AssignmentExpression; +exports.Binary = Binary; +exports.BinaryExpression = BinaryExpression; +exports.ClassExpression = ClassExpression; +exports.ConditionalExpression = ConditionalExpression; +exports.DoExpression = DoExpression; +exports.FunctionExpression = FunctionExpression; +exports.FunctionTypeAnnotation = FunctionTypeAnnotation; +exports.Identifier = Identifier; +exports.LogicalExpression = LogicalExpression; +exports.NullableTypeAnnotation = NullableTypeAnnotation; +exports.ObjectExpression = ObjectExpression; +exports.OptionalIndexedAccessType = OptionalIndexedAccessType; +exports.OptionalCallExpression = exports.OptionalMemberExpression = OptionalMemberExpression; +exports.SequenceExpression = SequenceExpression; +exports.TSAsExpression = TSAsExpression; +exports.TSInferType = TSInferType; +exports.TSInstantiationExpression = TSInstantiationExpression; +exports.TSTypeAssertion = TSTypeAssertion; +exports.TSIntersectionType = exports.TSUnionType = TSUnionType; +exports.UnaryLike = UnaryLike; +exports.IntersectionTypeAnnotation = exports.UnionTypeAnnotation = UnionTypeAnnotation; +exports.UpdateExpression = UpdateExpression; +exports.AwaitExpression = exports.YieldExpression = YieldExpression; + +var _t = require("@babel/types"); + +const { + isArrayTypeAnnotation, + isArrowFunctionExpression, + isAssignmentExpression, + isAwaitExpression, + isBinary, + isBinaryExpression, + isUpdateExpression, + isCallExpression, + isClass, + isClassExpression, + isConditional, + isConditionalExpression, + isExportDeclaration, + isExportDefaultDeclaration, + isExpressionStatement, + isFor, + isForInStatement, + isForOfStatement, + isForStatement, + isFunctionExpression, + isIfStatement, + isIndexedAccessType, + isIntersectionTypeAnnotation, + isLogicalExpression, + isMemberExpression, + isNewExpression, + isNullableTypeAnnotation, + isObjectPattern, + isOptionalCallExpression, + isOptionalMemberExpression, + isReturnStatement, + isSequenceExpression, + isSwitchStatement, + isTSArrayType, + isTSAsExpression, + isTSInstantiationExpression, + isTSIntersectionType, + isTSNonNullExpression, + isTSOptionalType, + isTSRestType, + isTSTypeAssertion, + isTSUnionType, + isTaggedTemplateExpression, + isThrowStatement, + isTypeAnnotation, + isUnaryLike, + isUnionTypeAnnotation, + isVariableDeclarator, + isWhileStatement, + isYieldExpression +} = _t; +const PRECEDENCE = { + "||": 0, + "??": 0, + "|>": 0, + "&&": 1, + "|": 2, + "^": 3, + "&": 4, + "==": 5, + "===": 5, + "!=": 5, + "!==": 5, + "<": 6, + ">": 6, + "<=": 6, + ">=": 6, + in: 6, + instanceof: 6, + ">>": 7, + "<<": 7, + ">>>": 7, + "+": 8, + "-": 8, + "*": 9, + "/": 9, + "%": 9, + "**": 10 +}; + +const isClassExtendsClause = (node, parent) => isClass(parent, { + superClass: node +}); + +const hasPostfixPart = (node, parent) => (isMemberExpression(parent) || isOptionalMemberExpression(parent)) && parent.object === node || (isCallExpression(parent) || isOptionalCallExpression(parent) || isNewExpression(parent)) && parent.callee === node || isTaggedTemplateExpression(parent) && parent.tag === node || isTSNonNullExpression(parent); + +function NullableTypeAnnotation(node, parent) { + return isArrayTypeAnnotation(parent); +} + +function FunctionTypeAnnotation(node, parent, printStack) { + if (printStack.length < 3) return; + return isUnionTypeAnnotation(parent) || isIntersectionTypeAnnotation(parent) || isArrayTypeAnnotation(parent) || isTypeAnnotation(parent) && isArrowFunctionExpression(printStack[printStack.length - 3]); +} + +function UpdateExpression(node, parent) { + return hasPostfixPart(node, parent) || isClassExtendsClause(node, parent); +} + +function ObjectExpression(node, parent, printStack) { + return isFirstInContext(printStack, 1 | 2); +} + +function DoExpression(node, parent, printStack) { + return !node.async && isFirstInContext(printStack, 1); +} + +function Binary(node, parent) { + if (node.operator === "**" && isBinaryExpression(parent, { + operator: "**" + })) { + return parent.left === node; + } + + if (isClassExtendsClause(node, parent)) { + return true; + } + + if (hasPostfixPart(node, parent) || isUnaryLike(parent) || isAwaitExpression(parent)) { + return true; + } + + if (isBinary(parent)) { + const parentOp = parent.operator; + const parentPos = PRECEDENCE[parentOp]; + const nodeOp = node.operator; + const nodePos = PRECEDENCE[nodeOp]; + + if (parentPos === nodePos && parent.right === node && !isLogicalExpression(parent) || parentPos > nodePos) { + return true; + } + } +} + +function UnionTypeAnnotation(node, parent) { + return isArrayTypeAnnotation(parent) || isNullableTypeAnnotation(parent) || isIntersectionTypeAnnotation(parent) || isUnionTypeAnnotation(parent); +} + +function OptionalIndexedAccessType(node, parent) { + return isIndexedAccessType(parent, { + objectType: node + }); +} + +function TSAsExpression() { + return true; +} + +function TSTypeAssertion() { + return true; +} + +function TSUnionType(node, parent) { + return isTSArrayType(parent) || isTSOptionalType(parent) || isTSIntersectionType(parent) || isTSUnionType(parent) || isTSRestType(parent); +} + +function TSInferType(node, parent) { + return isTSArrayType(parent) || isTSOptionalType(parent); +} + +function TSInstantiationExpression(node, parent) { + return (isCallExpression(parent) || isOptionalCallExpression(parent) || isNewExpression(parent) || isTSInstantiationExpression(parent)) && !!parent.typeParameters; +} + +function BinaryExpression(node, parent) { + return node.operator === "in" && (isVariableDeclarator(parent) || isFor(parent)); +} + +function SequenceExpression(node, parent) { + if (isForStatement(parent) || isThrowStatement(parent) || isReturnStatement(parent) || isIfStatement(parent) && parent.test === node || isWhileStatement(parent) && parent.test === node || isForInStatement(parent) && parent.right === node || isSwitchStatement(parent) && parent.discriminant === node || isExpressionStatement(parent) && parent.expression === node) { + return false; + } + + return true; +} + +function YieldExpression(node, parent) { + return isBinary(parent) || isUnaryLike(parent) || hasPostfixPart(node, parent) || isAwaitExpression(parent) && isYieldExpression(node) || isConditionalExpression(parent) && node === parent.test || isClassExtendsClause(node, parent); +} + +function ClassExpression(node, parent, printStack) { + return isFirstInContext(printStack, 1 | 4); +} + +function UnaryLike(node, parent) { + return hasPostfixPart(node, parent) || isBinaryExpression(parent, { + operator: "**", + left: node + }) || isClassExtendsClause(node, parent); +} + +function FunctionExpression(node, parent, printStack) { + return isFirstInContext(printStack, 1 | 4); +} + +function ArrowFunctionExpression(node, parent) { + return isExportDeclaration(parent) || ConditionalExpression(node, parent); +} + +function ConditionalExpression(node, parent) { + if (isUnaryLike(parent) || isBinary(parent) || isConditionalExpression(parent, { + test: node + }) || isAwaitExpression(parent) || isTSTypeAssertion(parent) || isTSAsExpression(parent)) { + return true; + } + + return UnaryLike(node, parent); +} + +function OptionalMemberExpression(node, parent) { + return isCallExpression(parent, { + callee: node + }) || isMemberExpression(parent, { + object: node + }); +} + +function AssignmentExpression(node, parent) { + if (isObjectPattern(node.left)) { + return true; + } else { + return ConditionalExpression(node, parent); + } +} + +function LogicalExpression(node, parent) { + switch (node.operator) { + case "||": + if (!isLogicalExpression(parent)) return false; + return parent.operator === "??" || parent.operator === "&&"; + + case "&&": + return isLogicalExpression(parent, { + operator: "??" + }); + + case "??": + return isLogicalExpression(parent) && parent.operator !== "??"; + } +} + +function Identifier(node, parent, printStack) { + var _node$extra; + + if ((_node$extra = node.extra) != null && _node$extra.parenthesized && isAssignmentExpression(parent, { + left: node + }) && (isFunctionExpression(parent.right) || isClassExpression(parent.right)) && parent.right.id == null) { + return true; + } + + if (node.name === "let") { + const isFollowedByBracket = isMemberExpression(parent, { + object: node, + computed: true + }) || isOptionalMemberExpression(parent, { + object: node, + computed: true, + optional: false + }); + return isFirstInContext(printStack, isFollowedByBracket ? 1 | 8 | 16 | 32 : 32); + } + + return node.name === "async" && isForOfStatement(parent) && node === parent.left; +} + +function isFirstInContext(printStack, checkParam) { + const expressionStatement = checkParam & 1; + const arrowBody = checkParam & 2; + const exportDefault = checkParam & 4; + const forHead = checkParam & 8; + const forInHead = checkParam & 16; + const forOfHead = checkParam & 32; + let i = printStack.length - 1; + if (i <= 0) return; + let node = printStack[i]; + i--; + let parent = printStack[i]; + + while (i >= 0) { + if (expressionStatement && isExpressionStatement(parent, { + expression: node + }) || exportDefault && isExportDefaultDeclaration(parent, { + declaration: node + }) || arrowBody && isArrowFunctionExpression(parent, { + body: node + }) || forHead && isForStatement(parent, { + init: node + }) || forInHead && isForInStatement(parent, { + left: node + }) || forOfHead && isForOfStatement(parent, { + left: node + })) { + return true; + } + + if (i > 0 && (hasPostfixPart(node, parent) && !isNewExpression(parent) || isSequenceExpression(parent) && parent.expressions[0] === node || isUpdateExpression(parent) && !parent.prefix || isConditional(parent, { + test: node + }) || isBinary(parent, { + left: node + }) || isAssignmentExpression(parent, { + left: node + }))) { + node = parent; + i--; + parent = printStack[i]; + } else { + return false; + } + } + + return false; +} + +//# sourceMappingURL=parentheses.js.map diff --git a/node_modules/@babel/generator/lib/node/parentheses.js.map b/node_modules/@babel/generator/lib/node/parentheses.js.map new file mode 100644 index 0000000..c743488 --- /dev/null +++ b/node_modules/@babel/generator/lib/node/parentheses.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isArrayTypeAnnotation","isArrowFunctionExpression","isAssignmentExpression","isAwaitExpression","isBinary","isBinaryExpression","isUpdateExpression","isCallExpression","isClass","isClassExpression","isConditional","isConditionalExpression","isExportDeclaration","isExportDefaultDeclaration","isExpressionStatement","isFor","isForInStatement","isForOfStatement","isForStatement","isFunctionExpression","isIfStatement","isIndexedAccessType","isIntersectionTypeAnnotation","isLogicalExpression","isMemberExpression","isNewExpression","isNullableTypeAnnotation","isObjectPattern","isOptionalCallExpression","isOptionalMemberExpression","isReturnStatement","isSequenceExpression","isSwitchStatement","isTSArrayType","isTSAsExpression","isTSInstantiationExpression","isTSIntersectionType","isTSNonNullExpression","isTSOptionalType","isTSRestType","isTSTypeAssertion","isTSUnionType","isTaggedTemplateExpression","isThrowStatement","isTypeAnnotation","isUnaryLike","isUnionTypeAnnotation","isVariableDeclarator","isWhileStatement","isYieldExpression","PRECEDENCE","in","instanceof","isClassExtendsClause","node","parent","superClass","hasPostfixPart","object","callee","tag","NullableTypeAnnotation","FunctionTypeAnnotation","printStack","length","UpdateExpression","ObjectExpression","isFirstInContext","DoExpression","async","Binary","operator","left","parentOp","parentPos","nodeOp","nodePos","right","UnionTypeAnnotation","OptionalIndexedAccessType","objectType","TSAsExpression","TSTypeAssertion","TSUnionType","TSInferType","TSInstantiationExpression","typeParameters","BinaryExpression","SequenceExpression","test","discriminant","expression","YieldExpression","ClassExpression","UnaryLike","FunctionExpression","ArrowFunctionExpression","ConditionalExpression","OptionalMemberExpression","AssignmentExpression","LogicalExpression","Identifier","extra","parenthesized","id","name","isFollowedByBracket","computed","optional","checkParam","expressionStatement","arrowBody","exportDefault","forHead","forInHead","forOfHead","i","declaration","body","init","expressions","prefix"],"sources":["../../src/node/parentheses.ts"],"sourcesContent":["import {\n isArrayTypeAnnotation,\n isArrowFunctionExpression,\n isAssignmentExpression,\n isAwaitExpression,\n isBinary,\n isBinaryExpression,\n isUpdateExpression,\n isCallExpression,\n isClass,\n isClassExpression,\n isConditional,\n isConditionalExpression,\n isExportDeclaration,\n isExportDefaultDeclaration,\n isExpressionStatement,\n isFor,\n isForInStatement,\n isForOfStatement,\n isForStatement,\n isFunctionExpression,\n isIfStatement,\n isIndexedAccessType,\n isIntersectionTypeAnnotation,\n isLogicalExpression,\n isMemberExpression,\n isNewExpression,\n isNullableTypeAnnotation,\n isObjectPattern,\n isOptionalCallExpression,\n isOptionalMemberExpression,\n isReturnStatement,\n isSequenceExpression,\n isSwitchStatement,\n isTSArrayType,\n isTSAsExpression,\n isTSInstantiationExpression,\n isTSIntersectionType,\n isTSNonNullExpression,\n isTSOptionalType,\n isTSRestType,\n isTSTypeAssertion,\n isTSUnionType,\n isTaggedTemplateExpression,\n isThrowStatement,\n isTypeAnnotation,\n isUnaryLike,\n isUnionTypeAnnotation,\n isVariableDeclarator,\n isWhileStatement,\n isYieldExpression,\n} from \"@babel/types\";\nimport type * as t from \"@babel/types\";\nconst PRECEDENCE = {\n \"||\": 0,\n \"??\": 0,\n \"|>\": 0,\n \"&&\": 1,\n \"|\": 2,\n \"^\": 3,\n \"&\": 4,\n \"==\": 5,\n \"===\": 5,\n \"!=\": 5,\n \"!==\": 5,\n \"<\": 6,\n \">\": 6,\n \"<=\": 6,\n \">=\": 6,\n in: 6,\n instanceof: 6,\n \">>\": 7,\n \"<<\": 7,\n \">>>\": 7,\n \"+\": 8,\n \"-\": 8,\n \"*\": 9,\n \"/\": 9,\n \"%\": 9,\n \"**\": 10,\n};\n\nconst enum CheckParam {\n expressionStatement = 1 << 0,\n arrowBody = 1 << 1,\n exportDefault = 1 << 2,\n forHead = 1 << 3,\n forInHead = 1 << 4,\n forOfHead = 1 << 5,\n}\n\nconst isClassExtendsClause = (\n node: t.Node,\n parent: t.Node,\n): parent is t.Class => isClass(parent, { superClass: node });\n\nconst hasPostfixPart = (node: t.Node, parent: t.Node) =>\n ((isMemberExpression(parent) || isOptionalMemberExpression(parent)) &&\n parent.object === node) ||\n ((isCallExpression(parent) ||\n isOptionalCallExpression(parent) ||\n isNewExpression(parent)) &&\n parent.callee === node) ||\n (isTaggedTemplateExpression(parent) && parent.tag === node) ||\n isTSNonNullExpression(parent);\n\nexport function NullableTypeAnnotation(\n node: t.NullableTypeAnnotation,\n parent: t.Node,\n): boolean {\n return isArrayTypeAnnotation(parent);\n}\n\nexport function FunctionTypeAnnotation(\n node: t.FunctionTypeAnnotation,\n parent: t.Node,\n printStack: Array,\n): boolean {\n if (printStack.length < 3) return;\n\n return (\n // (() => A) | (() => B)\n isUnionTypeAnnotation(parent) ||\n // (() => A) & (() => B)\n isIntersectionTypeAnnotation(parent) ||\n // (() => A)[]\n isArrayTypeAnnotation(parent) ||\n // (A: T): (T => T[]) => B => [A, B]\n (isTypeAnnotation(parent) &&\n // Check grandparent\n isArrowFunctionExpression(printStack[printStack.length - 3]))\n );\n}\n\nexport function UpdateExpression(\n node: t.UpdateExpression,\n parent: t.Node,\n): boolean {\n return hasPostfixPart(node, parent) || isClassExtendsClause(node, parent);\n}\n\nexport function ObjectExpression(\n node: t.ObjectExpression,\n parent: t.Node,\n printStack: Array,\n): boolean {\n return isFirstInContext(\n printStack,\n CheckParam.expressionStatement | CheckParam.arrowBody,\n );\n}\n\nexport function DoExpression(\n node: t.DoExpression,\n parent: t.Node,\n printStack: Array,\n): boolean {\n // `async do` can start an expression statement\n return (\n !node.async && isFirstInContext(printStack, CheckParam.expressionStatement)\n );\n}\n\nexport function Binary(node: t.BinaryExpression, parent: t.Node): boolean {\n if (\n node.operator === \"**\" &&\n isBinaryExpression(parent, { operator: \"**\" })\n ) {\n return parent.left === node;\n }\n\n if (isClassExtendsClause(node, parent)) {\n return true;\n }\n\n if (\n hasPostfixPart(node, parent) ||\n isUnaryLike(parent) ||\n isAwaitExpression(parent)\n ) {\n return true;\n }\n\n if (isBinary(parent)) {\n const parentOp = parent.operator;\n const parentPos = PRECEDENCE[parentOp];\n\n const nodeOp = node.operator;\n const nodePos = PRECEDENCE[nodeOp];\n\n if (\n // Logical expressions with the same precedence don't need parens.\n (parentPos === nodePos &&\n parent.right === node &&\n !isLogicalExpression(parent)) ||\n parentPos > nodePos\n ) {\n return true;\n }\n }\n}\n\nexport function UnionTypeAnnotation(\n node: t.UnionTypeAnnotation,\n parent: t.Node,\n): boolean {\n return (\n isArrayTypeAnnotation(parent) ||\n isNullableTypeAnnotation(parent) ||\n isIntersectionTypeAnnotation(parent) ||\n isUnionTypeAnnotation(parent)\n );\n}\n\nexport { UnionTypeAnnotation as IntersectionTypeAnnotation };\n\nexport function OptionalIndexedAccessType(\n node: t.OptionalIndexedAccessType,\n parent: t.Node,\n): boolean {\n return isIndexedAccessType(parent, { objectType: node });\n}\n\nexport function TSAsExpression() {\n return true;\n}\n\nexport function TSTypeAssertion() {\n return true;\n}\n\nexport function TSUnionType(node: t.TSUnionType, parent: t.Node): boolean {\n return (\n isTSArrayType(parent) ||\n isTSOptionalType(parent) ||\n isTSIntersectionType(parent) ||\n isTSUnionType(parent) ||\n isTSRestType(parent)\n );\n}\n\nexport { TSUnionType as TSIntersectionType };\n\nexport function TSInferType(node: t.TSInferType, parent: t.Node): boolean {\n return isTSArrayType(parent) || isTSOptionalType(parent);\n}\n\nexport function TSInstantiationExpression(\n node: t.TSInstantiationExpression,\n parent: t.Node,\n) {\n return (\n (isCallExpression(parent) ||\n isOptionalCallExpression(parent) ||\n isNewExpression(parent) ||\n isTSInstantiationExpression(parent)) &&\n !!parent.typeParameters\n );\n}\n\nexport function BinaryExpression(\n node: t.BinaryExpression,\n parent: t.Node,\n): boolean {\n // let i = (1 in []);\n // for ((1 in []);;);\n return (\n node.operator === \"in\" && (isVariableDeclarator(parent) || isFor(parent))\n );\n}\n\nexport function SequenceExpression(\n node: t.SequenceExpression,\n parent: t.Node,\n): boolean {\n if (\n // Although parentheses wouldn\"t hurt around sequence\n // expressions in the head of for loops, traditional style\n // dictates that e.g. i++, j++ should not be wrapped with\n // parentheses.\n isForStatement(parent) ||\n isThrowStatement(parent) ||\n isReturnStatement(parent) ||\n (isIfStatement(parent) && parent.test === node) ||\n (isWhileStatement(parent) && parent.test === node) ||\n (isForInStatement(parent) && parent.right === node) ||\n (isSwitchStatement(parent) && parent.discriminant === node) ||\n (isExpressionStatement(parent) && parent.expression === node)\n ) {\n return false;\n }\n\n // Otherwise err on the side of overparenthesization, adding\n // explicit exceptions above if this proves overzealous.\n return true;\n}\n\nexport function YieldExpression(\n node: t.YieldExpression,\n parent: t.Node,\n): boolean {\n return (\n isBinary(parent) ||\n isUnaryLike(parent) ||\n hasPostfixPart(node, parent) ||\n (isAwaitExpression(parent) && isYieldExpression(node)) ||\n (isConditionalExpression(parent) && node === parent.test) ||\n isClassExtendsClause(node, parent)\n );\n}\n\nexport { YieldExpression as AwaitExpression };\n\nexport function ClassExpression(\n node: t.ClassExpression,\n parent: t.Node,\n printStack: Array,\n): boolean {\n return isFirstInContext(\n printStack,\n CheckParam.expressionStatement | CheckParam.exportDefault,\n );\n}\n\nexport function UnaryLike(\n node:\n | t.UnaryLike\n | t.ArrowFunctionExpression\n | t.ConditionalExpression\n | t.AssignmentExpression,\n parent: t.Node,\n): boolean {\n return (\n hasPostfixPart(node, parent) ||\n isBinaryExpression(parent, { operator: \"**\", left: node }) ||\n isClassExtendsClause(node, parent)\n );\n}\n\nexport function FunctionExpression(\n node: t.FunctionExpression,\n parent: t.Node,\n printStack: Array,\n): boolean {\n return isFirstInContext(\n printStack,\n CheckParam.expressionStatement | CheckParam.exportDefault,\n );\n}\n\nexport function ArrowFunctionExpression(\n node: t.ArrowFunctionExpression,\n parent: t.Node,\n): boolean {\n return isExportDeclaration(parent) || ConditionalExpression(node, parent);\n}\n\nexport function ConditionalExpression(\n node:\n | t.ConditionalExpression\n | t.ArrowFunctionExpression\n | t.AssignmentExpression,\n parent?: t.Node,\n): boolean {\n if (\n isUnaryLike(parent) ||\n isBinary(parent) ||\n isConditionalExpression(parent, { test: node }) ||\n isAwaitExpression(parent) ||\n isTSTypeAssertion(parent) ||\n isTSAsExpression(parent)\n ) {\n return true;\n }\n\n return UnaryLike(node, parent);\n}\n\nexport function OptionalMemberExpression(\n node: t.OptionalMemberExpression,\n parent: t.Node,\n): boolean {\n return (\n isCallExpression(parent, { callee: node }) ||\n isMemberExpression(parent, { object: node })\n );\n}\n\nexport { OptionalMemberExpression as OptionalCallExpression };\n\nexport function AssignmentExpression(\n node: t.AssignmentExpression,\n parent: t.Node,\n): boolean {\n if (isObjectPattern(node.left)) {\n return true;\n } else {\n return ConditionalExpression(node, parent);\n }\n}\n\nexport function LogicalExpression(\n node: t.LogicalExpression,\n parent: t.Node,\n): boolean {\n switch (node.operator) {\n case \"||\":\n if (!isLogicalExpression(parent)) return false;\n return parent.operator === \"??\" || parent.operator === \"&&\";\n case \"&&\":\n return isLogicalExpression(parent, { operator: \"??\" });\n case \"??\":\n return isLogicalExpression(parent) && parent.operator !== \"??\";\n }\n}\n\nexport function Identifier(\n node: t.Identifier,\n parent: t.Node,\n printStack: Array,\n): boolean {\n // 13.15.2 AssignmentExpression RS: Evaluation\n // (fn) = function () {};\n if (\n node.extra?.parenthesized &&\n isAssignmentExpression(parent, { left: node }) &&\n (isFunctionExpression(parent.right) || isClassExpression(parent.right)) &&\n parent.right.id == null\n ) {\n return true;\n }\n // Non-strict code allows the identifier `let`, but it cannot occur as-is in\n // certain contexts to avoid ambiguity with contextual keyword `let`.\n if (node.name === \"let\") {\n // Some contexts only forbid `let [`, so check if the next token would\n // be the left bracket of a computed member expression.\n const isFollowedByBracket =\n isMemberExpression(parent, {\n object: node,\n computed: true,\n }) ||\n isOptionalMemberExpression(parent, {\n object: node,\n computed: true,\n optional: false,\n });\n return isFirstInContext(\n printStack,\n isFollowedByBracket\n ? CheckParam.expressionStatement |\n CheckParam.forHead |\n CheckParam.forInHead |\n CheckParam.forOfHead\n : CheckParam.forOfHead,\n );\n }\n\n // ECMAScript specifically forbids a for-of loop from starting with the\n // token sequence `for (async of`, because it would be ambiguous with\n // `for (async of => {};;)`, so we need to add extra parentheses.\n //\n // If the parent is a for-await-of loop (i.e. parent.await === true), the\n // parentheses aren't strictly needed, but we add them anyway because\n // some tools (including earlier Babel versions) can't parse\n // `for await (async of [])` without them.\n return (\n node.name === \"async\" && isForOfStatement(parent) && node === parent.left\n );\n}\n\n// Walk up the print stack to determine if our node can come first\n// in a particular context.\nfunction isFirstInContext(\n printStack: Array,\n checkParam: CheckParam,\n): boolean {\n const expressionStatement = checkParam & CheckParam.expressionStatement;\n const arrowBody = checkParam & CheckParam.arrowBody;\n const exportDefault = checkParam & CheckParam.exportDefault;\n const forHead = checkParam & CheckParam.forHead;\n const forInHead = checkParam & CheckParam.forInHead;\n const forOfHead = checkParam & CheckParam.forOfHead;\n\n let i = printStack.length - 1;\n if (i <= 0) return;\n let node = printStack[i];\n i--;\n let parent = printStack[i];\n while (i >= 0) {\n if (\n (expressionStatement &&\n isExpressionStatement(parent, { expression: node })) ||\n (exportDefault &&\n isExportDefaultDeclaration(parent, { declaration: node })) ||\n (arrowBody && isArrowFunctionExpression(parent, { body: node })) ||\n (forHead && isForStatement(parent, { init: node })) ||\n (forInHead && isForInStatement(parent, { left: node })) ||\n (forOfHead && isForOfStatement(parent, { left: node }))\n ) {\n return true;\n }\n\n if (\n i > 0 &&\n ((hasPostfixPart(node, parent) && !isNewExpression(parent)) ||\n (isSequenceExpression(parent) && parent.expressions[0] === node) ||\n (isUpdateExpression(parent) && !parent.prefix) ||\n isConditional(parent, { test: node }) ||\n isBinary(parent, { left: node }) ||\n isAssignmentExpression(parent, { left: node }))\n ) {\n node = parent;\n i--;\n parent = printStack[i];\n } else {\n return false;\n }\n }\n\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;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,MAAD,CAAlB,IAA8B,CAACA,MAAM,CAACkE,MAFxC,IAGC/G,aAAa,CAAC6C,MAAD,EAAS;MAAEkC,IAAI,EAAEnC;IAAR,CAAT,CAHd,IAIClD,QAAQ,CAACmD,MAAD,EAAS;MAAEiB,IAAI,EAAElB;IAAR,CAAT,CAJT,IAKCpD,sBAAsB,CAACqD,MAAD,EAAS;MAAEiB,IAAI,EAAElB;IAAR,CAAT,CANxB,CADF,EAQE;MACAA,IAAI,GAAGC,MAAP;MACA6D,CAAC;MACD7D,MAAM,GAAGQ,UAAU,CAACqD,CAAD,CAAnB;IACD,CAZD,MAYO;MACL,OAAO,KAAP;IACD;EACF;;EAED,OAAO,KAAP;AACD"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/node/whitespace.js b/node_modules/@babel/generator/lib/node/whitespace.js new file mode 100644 index 0000000..ccb5401 --- /dev/null +++ b/node_modules/@babel/generator/lib/node/whitespace.js @@ -0,0 +1,176 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.nodes = void 0; + +var _t = require("@babel/types"); + +const { + FLIPPED_ALIAS_KEYS, + isArrayExpression, + isAssignmentExpression, + isBinary, + isBlockStatement, + isCallExpression, + isFunction, + isIdentifier, + isLiteral, + isMemberExpression, + isObjectExpression, + isOptionalCallExpression, + isOptionalMemberExpression, + isStringLiteral +} = _t; + +function crawlInternal(node, state) { + if (!node) return state; + + if (isMemberExpression(node) || isOptionalMemberExpression(node)) { + crawlInternal(node.object, state); + if (node.computed) crawlInternal(node.property, state); + } else if (isBinary(node) || isAssignmentExpression(node)) { + crawlInternal(node.left, state); + crawlInternal(node.right, state); + } else if (isCallExpression(node) || isOptionalCallExpression(node)) { + state.hasCall = true; + crawlInternal(node.callee, state); + } else if (isFunction(node)) { + state.hasFunction = true; + } else if (isIdentifier(node)) { + state.hasHelper = state.hasHelper || node.callee && isHelper(node.callee); + } + + return state; +} + +function crawl(node) { + return crawlInternal(node, { + hasCall: false, + hasFunction: false, + hasHelper: false + }); +} + +function isHelper(node) { + if (!node) return false; + + if (isMemberExpression(node)) { + return isHelper(node.object) || isHelper(node.property); + } else if (isIdentifier(node)) { + return node.name === "require" || node.name.charCodeAt(0) === 95; + } else if (isCallExpression(node)) { + return isHelper(node.callee); + } else if (isBinary(node) || isAssignmentExpression(node)) { + return isIdentifier(node.left) && isHelper(node.left) || isHelper(node.right); + } else { + return false; + } +} + +function isType(node) { + return isLiteral(node) || isObjectExpression(node) || isArrayExpression(node) || isIdentifier(node) || isMemberExpression(node); +} + +const nodes = { + AssignmentExpression(node) { + const state = crawl(node.right); + + if (state.hasCall && state.hasHelper || state.hasFunction) { + return state.hasFunction ? 1 | 2 : 2; + } + }, + + SwitchCase(node, parent) { + return (!!node.consequent.length || parent.cases[0] === node ? 1 : 0) | (!node.consequent.length && parent.cases[parent.cases.length - 1] === node ? 2 : 0); + }, + + LogicalExpression(node) { + if (isFunction(node.left) || isFunction(node.right)) { + return 2; + } + }, + + Literal(node) { + if (isStringLiteral(node) && node.value === "use strict") { + return 2; + } + }, + + CallExpression(node) { + if (isFunction(node.callee) || isHelper(node)) { + return 1 | 2; + } + }, + + OptionalCallExpression(node) { + if (isFunction(node.callee)) { + return 1 | 2; + } + }, + + VariableDeclaration(node) { + for (let i = 0; i < node.declarations.length; i++) { + const declar = node.declarations[i]; + let enabled = isHelper(declar.id) && !isType(declar.init); + + if (!enabled && declar.init) { + const state = crawl(declar.init); + enabled = isHelper(declar.init) && state.hasCall || state.hasFunction; + } + + if (enabled) { + return 1 | 2; + } + } + }, + + IfStatement(node) { + if (isBlockStatement(node.consequent)) { + return 1 | 2; + } + } + +}; +exports.nodes = nodes; + +nodes.ObjectProperty = nodes.ObjectTypeProperty = nodes.ObjectMethod = function (node, parent) { + if (parent.properties[0] === node) { + return 1; + } +}; + +nodes.ObjectTypeCallProperty = function (node, parent) { + var _parent$properties; + + if (parent.callProperties[0] === node && !((_parent$properties = parent.properties) != null && _parent$properties.length)) { + return 1; + } +}; + +nodes.ObjectTypeIndexer = function (node, parent) { + var _parent$properties2, _parent$callPropertie; + + if (parent.indexers[0] === node && !((_parent$properties2 = parent.properties) != null && _parent$properties2.length) && !((_parent$callPropertie = parent.callProperties) != null && _parent$callPropertie.length)) { + return 1; + } +}; + +nodes.ObjectTypeInternalSlot = function (node, parent) { + var _parent$properties3, _parent$callPropertie2, _parent$indexers; + + if (parent.internalSlots[0] === node && !((_parent$properties3 = parent.properties) != null && _parent$properties3.length) && !((_parent$callPropertie2 = parent.callProperties) != null && _parent$callPropertie2.length) && !((_parent$indexers = parent.indexers) != null && _parent$indexers.length)) { + return 1; + } +}; + +[["Function", true], ["Class", true], ["Loop", true], ["LabeledStatement", true], ["SwitchStatement", true], ["TryStatement", true]].forEach(function ([type, amounts]) { + [type].concat(FLIPPED_ALIAS_KEYS[type] || []).forEach(function (type) { + const ret = amounts ? 1 | 2 : 0; + + nodes[type] = () => ret; + }); +}); + +//# sourceMappingURL=whitespace.js.map diff --git a/node_modules/@babel/generator/lib/node/whitespace.js.map b/node_modules/@babel/generator/lib/node/whitespace.js.map new file mode 100644 index 0000000..90fcd3f --- /dev/null +++ b/node_modules/@babel/generator/lib/node/whitespace.js.map @@ -0,0 +1 @@ +{"version":3,"names":["FLIPPED_ALIAS_KEYS","isArrayExpression","isAssignmentExpression","isBinary","isBlockStatement","isCallExpression","isFunction","isIdentifier","isLiteral","isMemberExpression","isObjectExpression","isOptionalCallExpression","isOptionalMemberExpression","isStringLiteral","crawlInternal","node","state","object","computed","property","left","right","hasCall","callee","hasFunction","hasHelper","isHelper","crawl","name","charCodeAt","isType","nodes","AssignmentExpression","SwitchCase","parent","consequent","length","cases","LogicalExpression","Literal","value","CallExpression","OptionalCallExpression","VariableDeclaration","i","declarations","declar","enabled","id","init","IfStatement","ObjectProperty","ObjectTypeProperty","ObjectMethod","properties","ObjectTypeCallProperty","callProperties","ObjectTypeIndexer","indexers","ObjectTypeInternalSlot","internalSlots","forEach","type","amounts","concat","ret"],"sources":["../../src/node/whitespace.ts"],"sourcesContent":["import {\n FLIPPED_ALIAS_KEYS,\n isArrayExpression,\n isAssignmentExpression,\n isBinary,\n isBlockStatement,\n isCallExpression,\n isFunction,\n isIdentifier,\n isLiteral,\n isMemberExpression,\n isObjectExpression,\n isOptionalCallExpression,\n isOptionalMemberExpression,\n isStringLiteral,\n} from \"@babel/types\";\nimport * as charCodes from \"charcodes\";\n\nimport type { NodeHandlers } from \"./index\";\n\nimport type * as t from \"@babel/types\";\n\nconst enum WhitespaceFlag {\n before = 1 << 0,\n after = 1 << 1,\n}\n\nexport type { WhitespaceFlag };\n\nfunction crawlInternal(\n node: t.Node,\n state: { hasCall: boolean; hasFunction: boolean; hasHelper: boolean },\n) {\n if (!node) return state;\n\n if (isMemberExpression(node) || isOptionalMemberExpression(node)) {\n crawlInternal(node.object, state);\n if (node.computed) crawlInternal(node.property, state);\n } else if (isBinary(node) || isAssignmentExpression(node)) {\n crawlInternal(node.left, state);\n crawlInternal(node.right, state);\n } else if (isCallExpression(node) || isOptionalCallExpression(node)) {\n state.hasCall = true;\n crawlInternal(node.callee, state);\n } else if (isFunction(node)) {\n state.hasFunction = true;\n } else if (isIdentifier(node)) {\n state.hasHelper =\n // @ts-expect-error todo(flow->ts): node.callee is not really expected here…\n state.hasHelper || (node.callee && isHelper(node.callee));\n }\n\n return state;\n}\n\n/**\n * Crawl a node to test if it contains a CallExpression, a Function, or a Helper.\n *\n * @example\n * crawl(node)\n * // { hasCall: false, hasFunction: true, hasHelper: false }\n */\n\nfunction crawl(node: t.Node) {\n return crawlInternal(node, {\n hasCall: false,\n hasFunction: false,\n hasHelper: false,\n });\n}\n\n/**\n * Test if a node is or has a helper.\n */\n\nfunction isHelper(node: t.Node): boolean {\n if (!node) return false;\n\n if (isMemberExpression(node)) {\n return isHelper(node.object) || isHelper(node.property);\n } else if (isIdentifier(node)) {\n return (\n node.name === \"require\" ||\n node.name.charCodeAt(0) === charCodes.underscore\n );\n } else if (isCallExpression(node)) {\n return isHelper(node.callee);\n } else if (isBinary(node) || isAssignmentExpression(node)) {\n return (\n (isIdentifier(node.left) && isHelper(node.left)) || isHelper(node.right)\n );\n } else {\n return false;\n }\n}\n\nfunction isType(node: t.Node) {\n return (\n isLiteral(node) ||\n isObjectExpression(node) ||\n isArrayExpression(node) ||\n isIdentifier(node) ||\n isMemberExpression(node)\n );\n}\n\n/**\n * Tests for node types that need whitespace.\n */\n\nexport const nodes: NodeHandlers = {\n /**\n * Test if AssignmentExpression needs whitespace.\n */\n\n AssignmentExpression(node: t.AssignmentExpression): WhitespaceFlag {\n const state = crawl(node.right);\n if ((state.hasCall && state.hasHelper) || state.hasFunction) {\n return state.hasFunction\n ? WhitespaceFlag.before | WhitespaceFlag.after\n : WhitespaceFlag.after;\n }\n },\n\n /**\n * Test if SwitchCase needs whitespace.\n */\n\n SwitchCase(node: t.SwitchCase, parent: t.SwitchStatement): WhitespaceFlag {\n return (\n (!!node.consequent.length || parent.cases[0] === node\n ? WhitespaceFlag.before\n : 0) |\n (!node.consequent.length && parent.cases[parent.cases.length - 1] === node\n ? WhitespaceFlag.after\n : 0)\n );\n },\n\n /**\n * Test if LogicalExpression needs whitespace.\n */\n\n LogicalExpression(node: t.LogicalExpression): WhitespaceFlag {\n if (isFunction(node.left) || isFunction(node.right)) {\n return WhitespaceFlag.after;\n }\n },\n\n /**\n * Test if Literal needs whitespace.\n */\n\n Literal(node: t.Literal): WhitespaceFlag {\n if (isStringLiteral(node) && node.value === \"use strict\") {\n return WhitespaceFlag.after;\n }\n },\n\n /**\n * Test if CallExpressionish needs whitespace.\n */\n\n CallExpression(node: t.CallExpression): WhitespaceFlag {\n if (isFunction(node.callee) || isHelper(node)) {\n return WhitespaceFlag.before | WhitespaceFlag.after;\n }\n },\n\n OptionalCallExpression(node: t.OptionalCallExpression): WhitespaceFlag {\n if (isFunction(node.callee)) {\n return WhitespaceFlag.before | WhitespaceFlag.after;\n }\n },\n\n /**\n * Test if VariableDeclaration needs whitespace.\n */\n\n VariableDeclaration(node: t.VariableDeclaration): WhitespaceFlag {\n for (let i = 0; i < node.declarations.length; i++) {\n const declar = node.declarations[i];\n\n let enabled = isHelper(declar.id) && !isType(declar.init);\n if (!enabled && declar.init) {\n const state = crawl(declar.init);\n enabled = (isHelper(declar.init) && state.hasCall) || state.hasFunction;\n }\n\n if (enabled) {\n return WhitespaceFlag.before | WhitespaceFlag.after;\n }\n }\n },\n\n /**\n * Test if IfStatement needs whitespace.\n */\n\n IfStatement(node: t.IfStatement): WhitespaceFlag {\n if (isBlockStatement(node.consequent)) {\n return WhitespaceFlag.before | WhitespaceFlag.after;\n }\n },\n};\n\n/**\n * Test if Property needs whitespace.\n */\n\nnodes.ObjectProperty =\n nodes.ObjectTypeProperty =\n nodes.ObjectMethod =\n function (\n node: t.ObjectProperty | t.ObjectTypeProperty | t.ObjectMethod,\n parent: t.ObjectExpression,\n ): WhitespaceFlag {\n if (parent.properties[0] === node) {\n return WhitespaceFlag.before;\n }\n };\n\nnodes.ObjectTypeCallProperty = function (\n node: t.ObjectTypeCallProperty,\n parent: t.ObjectTypeAnnotation,\n): WhitespaceFlag {\n if (parent.callProperties[0] === node && !parent.properties?.length) {\n return WhitespaceFlag.before;\n }\n};\n\nnodes.ObjectTypeIndexer = function (\n node: t.ObjectTypeIndexer,\n parent: t.ObjectTypeAnnotation,\n): WhitespaceFlag {\n if (\n parent.indexers[0] === node &&\n !parent.properties?.length &&\n !parent.callProperties?.length\n ) {\n return WhitespaceFlag.before;\n }\n};\n\nnodes.ObjectTypeInternalSlot = function (\n node: t.ObjectTypeInternalSlot,\n parent: t.ObjectTypeAnnotation,\n): WhitespaceFlag {\n if (\n parent.internalSlots[0] === node &&\n !parent.properties?.length &&\n !parent.callProperties?.length &&\n !parent.indexers?.length\n ) {\n return WhitespaceFlag.before;\n }\n};\n\n/**\n * Add whitespace tests for nodes and their aliases.\n */\n\n(\n [\n [\"Function\", true],\n [\"Class\", true],\n [\"Loop\", true],\n [\"LabeledStatement\", true],\n [\"SwitchStatement\", true],\n [\"TryStatement\", true],\n ] as const\n).forEach(function ([type, amounts]) {\n [type as string]\n .concat(FLIPPED_ALIAS_KEYS[type] || [])\n .forEach(function (type) {\n const ret = amounts ? WhitespaceFlag.before | WhitespaceFlag.after : 0;\n nodes[type] = () => ret;\n });\n});\n"],"mappings":";;;;;;;AAAA;;;EACEA,kB;EACAC,iB;EACAC,sB;EACAC,Q;EACAC,gB;EACAC,gB;EACAC,U;EACAC,Y;EACAC,S;EACAC,kB;EACAC,kB;EACAC,wB;EACAC,0B;EACAC;;;AAeF,SAASC,aAAT,CACEC,IADF,EAEEC,KAFF,EAGE;EACA,IAAI,CAACD,IAAL,EAAW,OAAOC,KAAP;;EAEX,IAAIP,kBAAkB,CAACM,IAAD,CAAlB,IAA4BH,0BAA0B,CAACG,IAAD,CAA1D,EAAkE;IAChED,aAAa,CAACC,IAAI,CAACE,MAAN,EAAcD,KAAd,CAAb;IACA,IAAID,IAAI,CAACG,QAAT,EAAmBJ,aAAa,CAACC,IAAI,CAACI,QAAN,EAAgBH,KAAhB,CAAb;EACpB,CAHD,MAGO,IAAIb,QAAQ,CAACY,IAAD,CAAR,IAAkBb,sBAAsB,CAACa,IAAD,CAA5C,EAAoD;IACzDD,aAAa,CAACC,IAAI,CAACK,IAAN,EAAYJ,KAAZ,CAAb;IACAF,aAAa,CAACC,IAAI,CAACM,KAAN,EAAaL,KAAb,CAAb;EACD,CAHM,MAGA,IAAIX,gBAAgB,CAACU,IAAD,CAAhB,IAA0BJ,wBAAwB,CAACI,IAAD,CAAtD,EAA8D;IACnEC,KAAK,CAACM,OAAN,GAAgB,IAAhB;IACAR,aAAa,CAACC,IAAI,CAACQ,MAAN,EAAcP,KAAd,CAAb;EACD,CAHM,MAGA,IAAIV,UAAU,CAACS,IAAD,CAAd,EAAsB;IAC3BC,KAAK,CAACQ,WAAN,GAAoB,IAApB;EACD,CAFM,MAEA,IAAIjB,YAAY,CAACQ,IAAD,CAAhB,EAAwB;IA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V,EAAgB;IACvB,MAAMG,GAAG,GAAGF,OAAO,GAAG,KAAH,GAAkD,CAArE;;IACAhC,KAAK,CAAC+B,IAAD,CAAL,GAAc,MAAMG,GAApB;EACD,CALH;AAMD,CAhBD"} \ No newline at end of file diff --git a/node_modules/@babel/generator/lib/printer.js b/node_modules/@babel/generator/lib/printer.js new file mode 100644 index 0000000..2c2d065 --- /dev/null +++ b/node_modules/@babel/generator/lib/printer.js @@ -0,0 +1,775 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _buffer = require("./buffer"); + +var n = require("./node"); + +var _t = require("@babel/types"); + +var generatorFunctions = require("./generators"); + +const { + isFunction, + isStatement, + isClassBody, + isTSInterfaceBody +} = _t; +const SCIENTIFIC_NOTATION = /e/i; +const ZERO_DECIMAL_INTEGER = /\.0+$/; +const NON_DECIMAL_LITERAL = /^0[box]/; +const PURE_ANNOTATION_RE = /^\s*[@#]__PURE__\s*$/; +const { + needsParens +} = n; + +class Printer { + constructor(format, map) { + this.inForStatementInitCounter = 0; + this._printStack = []; + this._indent = 0; + this._indentChar = 0; + this._indentRepeat = 0; + this._insideAux = false; + this._parenPushNewlineState = null; + this._noLineTerminator = false; + this._printAuxAfterOnNextUserNode = false; + this._printedComments = new Set(); + this._endsWithInteger = false; + this._endsWithWord = false; + this._lastCommentLine = 0; + this.format = format; + this._buf = new _buffer.default(map); + this._indentChar = format.indent.style.charCodeAt(0); + this._indentRepeat = format.indent.style.length; + } + + generate(ast) { + this.print(ast); + + this._maybeAddAuxComment(); + + return this._buf.get(); + } + + indent() { + if (this.format.compact || this.format.concise) return; + this._indent++; + } + + dedent() { + if (this.format.compact || this.format.concise) return; + this._indent--; + } + + semicolon(force = false) { + this._maybeAddAuxComment(); + + if (force) { + this._appendChar(59); + } else { + this._queue(59); + } + } + + rightBrace() { + if (this.format.minified) { + this._buf.removeLastSemicolon(); + } + + this.tokenChar(125); + } + + space(force = false) { + if (this.format.compact) return; + + if (force) { + this._space(); + } else if (this._buf.hasContent()) { + const lastCp = this.getLastChar(); + + if (lastCp !== 32 && lastCp !== 10) { + this._space(); + } + } + } + + word(str) { + if (this._endsWithWord || str.charCodeAt(0) === 47 && this.endsWith(47)) { + this._space(); + } + + this._maybeAddAuxComment(); + + this._append(str, false); + + this._endsWithWord = true; + } + + number(str) { + this.word(str); + this._endsWithInteger = Number.isInteger(+str) && !NON_DECIMAL_LITERAL.test(str) && !SCIENTIFIC_NOTATION.test(str) && !ZERO_DECIMAL_INTEGER.test(str) && str.charCodeAt(str.length - 1) !== 46; + } + + token(str, maybeNewline = false) { + const lastChar = this.getLastChar(); + const strFirst = str.charCodeAt(0); + + if (lastChar === 33 && str === "--" || strFirst === 43 && lastChar === 43 || strFirst === 45 && lastChar === 45 || strFirst === 46 && this._endsWithInteger) { + this._space(); + } + + this._maybeAddAuxComment(); + + this._append(str, maybeNewline); + } + + tokenChar(char) { + const lastChar = this.getLastChar(); + + if (char === 43 && lastChar === 43 || char === 45 && lastChar === 45 || char === 46 && this._endsWithInteger) { + this._space(); + } + + this._maybeAddAuxComment(); + + this._appendChar(char); + } + + newline(i = 1, force) { + if (i <= 0) return; + + if (!force) { + if (this.format.retainLines || this.format.compact) return; + + if (this.format.concise) { + this.space(); + return; + } + } + + if (i > 2) i = 2; + i -= this._buf.getNewlineCount(); + + for (let j = 0; j < i; j++) { + this._newline(); + } + + return; + } + + endsWith(char) { + return this.getLastChar() === char; + } + + getLastChar() { + return this._buf.getLastChar(); + } + + endsWithCharAndNewline() { + return this._buf.endsWithCharAndNewline(); + } + + removeTrailingNewline() { + this._buf.removeTrailingNewline(); + } + + exactSource(loc, cb) { + if (!loc) return cb(); + + this._catchUp("start", loc); + + this._buf.exactSource(loc, cb); + } + + source(prop, loc) { + if (!loc) return; + + this._catchUp(prop, loc); + + this._buf.source(prop, loc); + } + + sourceWithOffset(prop, loc, lineOffset, columnOffset) { + if (!loc) return; + + this._catchUp(prop, loc); + + this._buf.sourceWithOffset(prop, loc, lineOffset, columnOffset); + } + + withSource(prop, loc, cb) { + if (!loc) return cb(); + + this._catchUp(prop, loc); + + this._buf.withSource(prop, loc, cb); + } + + _space() { + this._queue(32); + } + + _newline() { + this._queue(10); + } + + _append(str, maybeNewline) { + this._maybeAddParen(str); + + this._maybeIndent(str.charCodeAt(0)); + + this._buf.append(str, maybeNewline); + + this._endsWithWord = false; + this._endsWithInteger = false; + } + + _appendChar(char) { + this._maybeAddParenChar(char); + + this._maybeIndent(char); + + this._buf.appendChar(char); + + this._endsWithWord = false; + this._endsWithInteger = false; + } + + _queue(char) { + this._maybeAddParenChar(char); + + this._maybeIndent(char); + + this._buf.queue(char); + + this._endsWithWord = false; + this._endsWithInteger = false; + } + + _maybeIndent(firstChar) { + if (this._indent && firstChar !== 10 && this.endsWith(10)) { + this._buf.queueIndentation(this._indentChar, this._getIndent()); + } + } + + _shouldIndent(firstChar) { + if (this._indent && firstChar !== 10 && this.endsWith(10)) { + return true; + } + } + + _maybeAddParenChar(char) { + const parenPushNewlineState = this._parenPushNewlineState; + if (!parenPushNewlineState) return; + + if (char === 32) { + return; + } + + if (char !== 10) { + this._parenPushNewlineState = null; + return; + } + + this.tokenChar(40); + this.indent(); + parenPushNewlineState.printed = true; + } + + _maybeAddParen(str) { + const parenPushNewlineState = this._parenPushNewlineState; + if (!parenPushNewlineState) return; + const len = str.length; + let i; + + for (i = 0; i < len && str.charCodeAt(i) === 32; i++) continue; + + if (i === len) { + return; + } + + const cha = str.charCodeAt(i); + + if (cha !== 10) { + if (cha !== 47 || i + 1 === len) { + this._parenPushNewlineState = null; + return; + } + + const chaPost = str.charCodeAt(i + 1); + + if (chaPost === 42) { + if (PURE_ANNOTATION_RE.test(str.slice(i + 2, len - 2))) { + return; + } + } else if (chaPost !== 47) { + this._parenPushNewlineState = null; + return; + } + } + + this.tokenChar(40); + this.indent(); + parenPushNewlineState.printed = true; + } + + catchUp(line) { + if (!this.format.retainLines) return; + + const count = line - this._buf.getCurrentLine(); + + for (let i = 0; i < count; i++) { + this._newline(); + } + } + + _catchUp(prop, loc) { + if (!this.format.retainLines) return; + const pos = loc ? loc[prop] : null; + + if ((pos == null ? void 0 : pos.line) != null) { + const count = pos.line - this._buf.getCurrentLine(); + + for (let i = 0; i < count; i++) { + this._newline(); + } + } + } + + _getIndent() { + return this._indentRepeat * this._indent; + } + + ensureNoLineTerminator(fn) { + const { + _noLineTerminator + } = this; + this._noLineTerminator = true; + fn(); + this._noLineTerminator = _noLineTerminator; + } + + printTerminatorless(node, parent, isLabel) { + if (isLabel) { + this.ensureNoLineTerminator(() => { + this.print(node, parent); + }); + } else { + const terminatorState = { + printed: false + }; + this._parenPushNewlineState = terminatorState; + this.print(node, parent); + + if (terminatorState.printed) { + this.dedent(); + this.newline(); + this.tokenChar(41); + } + } + } + + print(node, parent, noLineTerminator, trailingCommentsLineOffset) { + if (!node) return; + const nodeType = node.type; + const format = this.format; + const oldConcise = format.concise; + + if (node._compact) { + format.concise = true; + } + + const printMethod = this[nodeType]; + + if (printMethod === undefined) { + throw new ReferenceError(`unknown node of type ${JSON.stringify(nodeType)} with constructor ${JSON.stringify(node.constructor.name)}`); + } + + this._printStack.push(node); + + const oldInAux = this._insideAux; + this._insideAux = node.loc == undefined; + + this._maybeAddAuxComment(this._insideAux && !oldInAux); + + let shouldPrintParens = false; + + if (format.retainFunctionParens && nodeType === "FunctionExpression" && node.extra && node.extra.parenthesized) { + shouldPrintParens = true; + } else { + shouldPrintParens = needsParens(node, parent, this._printStack); + } + + if (shouldPrintParens) this.tokenChar(40); + this._lastCommentLine = 0; + + this._printLeadingComments(node, parent); + + const loc = nodeType === "Program" || nodeType === "File" ? null : node.loc; + this.exactSource(loc, printMethod.bind(this, node, parent)); + + if (noLineTerminator && !this._noLineTerminator) { + this._noLineTerminator = true; + + this._printTrailingComments(node, parent); + + this._noLineTerminator = false; + } else { + this._printTrailingComments(node, parent, trailingCommentsLineOffset); + } + + if (shouldPrintParens) this.tokenChar(41); + + this._printStack.pop(); + + format.concise = oldConcise; + this._insideAux = oldInAux; + } + + _maybeAddAuxComment(enteredPositionlessNode) { + if (enteredPositionlessNode) this._printAuxBeforeComment(); + if (!this._insideAux) this._printAuxAfterComment(); + } + + _printAuxBeforeComment() { + if (this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = true; + const comment = this.format.auxiliaryCommentBefore; + + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }, 0); + } + } + + _printAuxAfterComment() { + if (!this._printAuxAfterOnNextUserNode) return; + this._printAuxAfterOnNextUserNode = false; + const comment = this.format.auxiliaryCommentAfter; + + if (comment) { + this._printComment({ + type: "CommentBlock", + value: comment + }, 0); + } + } + + getPossibleRaw(node) { + const extra = node.extra; + + if (extra && extra.raw != null && extra.rawValue != null && node.value === extra.rawValue) { + return extra.raw; + } + } + + printJoin(nodes, parent, opts = {}) { + if (!(nodes != null && nodes.length)) return; + if (opts.indent) this.indent(); + const newlineOpts = { + addNewlines: opts.addNewlines, + nextNodeStartLine: 0 + }; + const separator = opts.separator ? opts.separator.bind(this) : null; + const len = nodes.length; + + for (let i = 0; i < len; i++) { + const node = nodes[i]; + if (!node) continue; + if (opts.statement) this._printNewline(i === 0, newlineOpts); + this.print(node, parent, undefined, opts.trailingCommentsLineOffset || 0); + opts.iterator == null ? void 0 : opts.iterator(node, i); + if (i < len - 1) separator == null ? void 0 : separator(); + + if (opts.statement) { + if (i + 1 === len) { + this.newline(1); + } else { + var _nextNode$loc; + + const nextNode = nodes[i + 1]; + newlineOpts.nextNodeStartLine = ((_nextNode$loc = nextNode.loc) == null ? void 0 : _nextNode$loc.start.line) || 0; + + this._printNewline(true, newlineOpts); + } + } + } + + if (opts.indent) this.dedent(); + } + + printAndIndentOnComments(node, parent) { + const indent = node.leadingComments && node.leadingComments.length > 0; + if (indent) this.indent(); + this.print(node, parent); + if (indent) this.dedent(); + } + + printBlock(parent) { + const node = parent.body; + + if (node.type !== "EmptyStatement") { + this.space(); + } + + this.print(node, parent); + } + + _printTrailingComments(node, parent, lineOffset) { + const comments = this._getComments(false, node); + + if (!(comments != null && comments.length)) return; + + this._printComments(2, comments, node, parent, lineOffset); + } + + _printLeadingComments(node, parent) { + const comments = this._getComments(true, node); + + if (!(comments != null && comments.length)) return; + + this._printComments(0, comments, node, parent); + } + + printInnerComments(node, indent = true) { + var _node$innerComments; + + if (!((_node$innerComments = node.innerComments) != null && _node$innerComments.length)) return; + if (indent) this.indent(); + + this._printComments(1, node.innerComments, node); + + if (indent) this.dedent(); + } + + printSequence(nodes, parent, opts = {}) { + opts.statement = true; + return this.printJoin(nodes, parent, opts); + } + + printList(items, parent, opts = {}) { + if (opts.separator == null) { + opts.separator = commaSeparator; + } + + return this.printJoin(items, parent, opts); + } + + _printNewline(newLine, opts) { + if (this.format.retainLines || this.format.compact) return; + + if (this.format.concise) { + this.space(); + return; + } + + if (!newLine) { + return; + } + + const startLine = opts.nextNodeStartLine; + const lastCommentLine = this._lastCommentLine; + + if (startLine > 0 && lastCommentLine > 0) { + const offset = startLine - lastCommentLine; + + if (offset >= 0) { + this.newline(offset || 1); + return; + } + } + + if (this._buf.hasContent()) { + this.newline(1); + } + } + + _getComments(leading, node) { + return node && (leading ? node.leadingComments : node.trailingComments) || null; + } + + _printComment(comment, skipNewLines) { + if (comment.ignore) return; + if (this._printedComments.has(comment)) return; + if (!this.format.shouldPrintComment(comment.value)) return; + + this._printedComments.add(comment); + + const isBlockComment = comment.type === "CommentBlock"; + const printNewLines = isBlockComment && skipNewLines !== 1 && !this._noLineTerminator; + + if (printNewLines && this._buf.hasContent() && skipNewLines !== 2) { + this.newline(1); + } + + const lastCharCode = this.getLastChar(); + + if (lastCharCode !== 91 && lastCharCode !== 123) { + this.space(); + } + + let val; + + if (isBlockComment) { + val = `/*${comment.value}*/`; + + if (this.format.indent.adjustMultilineComment) { + var _comment$loc; + + const offset = (_comment$loc = comment.loc) == null ? void 0 : _comment$loc.start.column; + + if (offset) { + const newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); + val = val.replace(newlineRegex, "\n"); + } + + let indentSize = this.format.retainLines ? 0 : this._buf.getCurrentColumn(); + + if (this._shouldIndent(47) || this.format.retainLines) { + indentSize += this._getIndent(); + } + + val = val.replace(/\n(?!$)/g, `\n${" ".repeat(indentSize)}`); + } + } else if (!this._noLineTerminator) { + val = `//${comment.value}`; + } else { + val = `/*${comment.value}*/`; + } + + if (this.endsWith(47)) this._space(); + this.source("start", comment.loc); + + this._append(val, isBlockComment); + + if (!isBlockComment && !this._noLineTerminator) { + this.newline(1, true); + } + + if (printNewLines && skipNewLines !== 3) { + this.newline(1); + } + } + + _printComments(type, comments, node, parent, lineOffset = 0) { + { + const nodeLoc = node.loc; + const len = comments.length; + let hasLoc = !!nodeLoc; + const nodeStartLine = hasLoc ? nodeLoc.start.line : 0; + const nodeEndLine = hasLoc ? nodeLoc.end.line : 0; + let lastLine = 0; + let leadingCommentNewline = 0; + + for (let i = 0; i < len; i++) { + const comment = comments[i]; + + if (hasLoc && comment.loc && !this._printedComments.has(comment)) { + const commentStartLine = comment.loc.start.line; + const commentEndLine = comment.loc.end.line; + + if (type === 0) { + let offset = 0; + + if (i === 0) { + if (this._buf.hasContent() && (comment.type === "CommentLine" || commentStartLine != commentEndLine)) { + offset = leadingCommentNewline = 1; + } + } else { + offset = commentStartLine - lastLine; + } + + lastLine = commentEndLine; + this.newline(offset); + + this._printComment(comment, 1); + + if (i + 1 === len) { + this.newline(Math.max(nodeStartLine - lastLine, leadingCommentNewline)); + lastLine = nodeStartLine; + } + } else if (type === 1) { + const offset = commentStartLine - (i === 0 ? nodeStartLine : lastLine); + lastLine = commentEndLine; + this.newline(offset); + + this._printComment(comment, 1); + + if (i + 1 === len) { + this.newline(Math.min(1, nodeEndLine - lastLine)); + lastLine = nodeEndLine; + } + } else { + const offset = commentStartLine - (i === 0 ? nodeEndLine - lineOffset : lastLine); + lastLine = commentEndLine; + this.newline(offset); + + this._printComment(comment, 1); + } + } else { + hasLoc = false; + + if (len === 1) { + const singleLine = comment.loc ? comment.loc.start.line === comment.loc.end.line : !comment.value.includes("\n"); + const shouldSkipNewline = singleLine && !isStatement(node) && !isClassBody(parent) && !isTSInterfaceBody(parent); + + if (type === 0) { + this._printComment(comment, shouldSkipNewline && node.type !== "ObjectExpression" || singleLine && isFunction(parent, { + body: node + }) ? 1 : 0); + } else if (shouldSkipNewline && type === 2) { + this._printComment(comment, 1); + } else { + this._printComment(comment, 0); + } + } else if (type === 1 && !(node.type === "ObjectExpression" && node.properties.length > 1) && node.type !== "ClassBody" && node.type !== "TSInterfaceBody") { + this._printComment(comment, i === 0 ? 2 : i === len - 1 ? 3 : 0); + } else { + this._printComment(comment, 0); + } + } + } + + if (type === 2 && hasLoc && lastLine) { + this._lastCommentLine = lastLine; + } + } + } + + printAssertions(node) { + var _node$assertions; + + if ((_node$assertions = node.assertions) != null && _node$assertions.length) { + this.space(); + this.word("assert"); + this.space(); + this.tokenChar(123); + this.space(); + this.printList(node.assertions, node); + this.space(); + this.tokenChar(125); + } + } + +} + +Object.assign(Printer.prototype, generatorFunctions); +{ + Printer.prototype.Noop = function Noop() {}; +} +var _default = Printer; +exports.default = _default; + +function commaSeparator() { + this.tokenChar(44); + this.space(); +} + +//# sourceMappingURL=printer.js.map diff --git a/node_modules/@babel/generator/lib/printer.js.map b/node_modules/@babel/generator/lib/printer.js.map new file mode 100644 index 0000000..7540cc5 --- /dev/null +++ b/node_modules/@babel/generator/lib/printer.js.map @@ -0,0 +1 @@ +{"version":3,"names":["isFunction","isStatement","isClassBody","isTSInterfaceBody","SCIENTIFIC_NOTATION","ZERO_DECIMAL_INTEGER","NON_DECIMAL_LITERAL","PURE_ANNOTATION_RE","needsParens","n","Printer","constructor","format","map","inForStatementInitCounter","_printStack","_indent","_indentChar","_indentRepeat","_insideAux","_parenPushNewlineState","_noLineTerminator","_printAuxAfterOnNextUserNode","_printedComments","Set","_endsWithInteger","_endsWithWord","_lastCommentLine","_buf","Buffer","indent","style","charCodeAt","length","generate","ast","print","_maybeAddAuxComment","get","compact","concise","dedent","semicolon","force","_appendChar","_queue","rightBrace","minified","removeLastSemicolon","token","space","_space","hasContent","lastCp","getLastChar","word","str","endsWith","_append","number","Number","isInteger","test","maybeNewline","lastChar","strFirst","tokenChar","char","newline","i","retainLines","getNewlineCount","j","_newline","endsWithCharAndNewline","removeTrailingNewline","exactSource","loc","cb","_catchUp","source","prop","sourceWithOffset","lineOffset","columnOffset","withSource","_maybeAddParen","_maybeIndent","append","_maybeAddParenChar","appendChar","queue","firstChar","queueIndentation","_getIndent","_shouldIndent","parenPushNewlineState","printed","len","cha","chaPost","slice","catchUp","line","count","getCurrentLine","pos","ensureNoLineTerminator","fn","printTerminatorless","node","parent","isLabel","terminatorState","noLineTerminator","trailingCommentsLineOffset","nodeType","type","oldConcise","_compact","printMethod","undefined","ReferenceError","JSON","stringify","name","push","oldInAux","shouldPrintParens","retainFunctionParens","extra","parenthesized","_printLeadingComments","bind","_printTrailingComments","pop","enteredPositionlessNode","_printAuxBeforeComment","_printAuxAfterComment","comment","auxiliaryCommentBefore","_printComment","value","auxiliaryCommentAfter","getPossibleRaw","raw","rawValue","printJoin","nodes","opts","newlineOpts","addNewlines","nextNodeStartLine","separator","statement","_printNewline","iterator","nextNode","start","printAndIndentOnComments","leadingComments","printBlock","body","comments","_getComments","_printComments","printInnerComments","innerComments","printSequence","printList","items","commaSeparator","newLine","startLine","lastCommentLine","offset","leading","trailingComments","skipNewLines","ignore","has","shouldPrintComment","add","isBlockComment","printNewLines","lastCharCode","val","adjustMultilineComment","column","newlineRegex","RegExp","replace","indentSize","getCurrentColumn","repeat","nodeLoc","hasLoc","nodeStartLine","nodeEndLine","end","lastLine","leadingCommentNewline","commentStartLine","commentEndLine","Math","max","min","singleLine","includes","shouldSkipNewline","properties","printAssertions","assertions","Object","assign","prototype","generatorFunctions","Noop"],"sources":["../src/printer.ts"],"sourcesContent":["import Buffer from \"./buffer\";\nimport type { Loc } from \"./buffer\";\nimport * as n from \"./node\";\nimport type * as t from \"@babel/types\";\nimport {\n isFunction,\n isStatement,\n isClassBody,\n isTSInterfaceBody,\n} from \"@babel/types\";\nimport type {\n RecordAndTuplePluginOptions,\n PipelineOperatorPluginOptions,\n} from \"@babel/parser\";\nimport type { Opts as jsescOptions } from \"jsesc\";\n\nimport * as generatorFunctions from \"./generators\";\nimport type SourceMap from \"./source-map\";\nimport * as charCodes from \"charcodes\";\n\nconst SCIENTIFIC_NOTATION = /e/i;\nconst ZERO_DECIMAL_INTEGER = /\\.0+$/;\nconst NON_DECIMAL_LITERAL = /^0[box]/;\nconst PURE_ANNOTATION_RE = /^\\s*[@#]__PURE__\\s*$/;\n\nconst { needsParens } = n;\n\nconst enum COMMENT_TYPE {\n LEADING,\n INNER,\n TRAILING,\n}\n\nconst enum COMMENT_SKIP_NEWLINE {\n DEFAULT,\n SKIP_ALL,\n SKIP_LEADING,\n SKIP_TRAILING,\n}\n\nexport type Format = {\n shouldPrintComment: (comment: string) => boolean;\n retainLines: boolean;\n retainFunctionParens: boolean;\n comments: boolean;\n auxiliaryCommentBefore: string;\n auxiliaryCommentAfter: string;\n compact: boolean | \"auto\";\n minified: boolean;\n concise: boolean;\n indent: {\n adjustMultilineComment: boolean;\n style: string;\n };\n recordAndTupleSyntaxType: RecordAndTuplePluginOptions[\"syntaxType\"];\n jsescOption: jsescOptions;\n jsonCompatibleStrings?: boolean;\n /**\n * For use with the Hack-style pipe operator.\n * Changes what token is used for pipe bodies’ topic references.\n */\n topicToken?: PipelineOperatorPluginOptions[\"topicToken\"];\n /**\n * @deprecated Removed in Babel 8\n */\n decoratorsBeforeExport?: boolean;\n};\n\ninterface AddNewlinesOptions {\n addNewlines(leading: boolean, node: t.Node): number;\n nextNodeStartLine: number;\n}\n\ninterface PrintSequenceOptions extends Partial {\n statement?: boolean;\n indent?: boolean;\n trailingCommentsLineOffset?: number;\n}\n\ninterface PrintListOptions {\n separator?: (this: Printer) => void;\n statement?: boolean;\n indent?: boolean;\n}\n\ntype PrintJoinOptions = PrintListOptions &\n PrintSequenceOptions & {\n iterator?: (node: t.Node, index: number) => void;\n };\nclass Printer {\n constructor(format: Format, map: SourceMap) {\n this.format = format;\n this._buf = new Buffer(map);\n\n this._indentChar = format.indent.style.charCodeAt(0);\n this._indentRepeat = format.indent.style.length;\n }\n\n declare format: Format;\n inForStatementInitCounter: number = 0;\n\n declare _buf: Buffer;\n _printStack: Array = [];\n _indent: number = 0;\n _indentChar: number = 0;\n _indentRepeat: number = 0;\n _insideAux: boolean = false;\n _parenPushNewlineState: { printed: boolean } | null = null;\n _noLineTerminator: boolean = false;\n _printAuxAfterOnNextUserNode: boolean = false;\n _printedComments = new Set();\n _endsWithInteger = false;\n _endsWithWord = false;\n _lastCommentLine = 0;\n\n generate(ast: t.Node) {\n this.print(ast);\n this._maybeAddAuxComment();\n\n return this._buf.get();\n }\n\n /**\n * Increment indent size.\n */\n\n indent(): void {\n if (this.format.compact || this.format.concise) return;\n\n this._indent++;\n }\n\n /**\n * Decrement indent size.\n */\n\n dedent(): void {\n if (this.format.compact || this.format.concise) return;\n\n this._indent--;\n }\n\n /**\n * Add a semicolon to the buffer.\n */\n\n semicolon(force: boolean = false): void {\n this._maybeAddAuxComment();\n if (force) {\n this._appendChar(charCodes.semicolon);\n } else {\n this._queue(charCodes.semicolon);\n }\n }\n\n /**\n * Add a right brace to the buffer.\n */\n\n rightBrace(): void {\n if (this.format.minified) {\n this._buf.removeLastSemicolon();\n }\n this.token(\"}\");\n }\n\n /**\n * Add a space to the buffer unless it is compact.\n */\n\n space(force: boolean = false): void {\n if (this.format.compact) return;\n\n if (force) {\n this._space();\n } else if (this._buf.hasContent()) {\n const lastCp = this.getLastChar();\n if (lastCp !== charCodes.space && lastCp !== charCodes.lineFeed) {\n this._space();\n }\n }\n }\n\n /**\n * Writes a token that can't be safely parsed without taking whitespace into account.\n */\n\n word(str: string): void {\n // prevent concatenating words and creating // comment out of division and regex\n if (\n this._endsWithWord ||\n (str.charCodeAt(0) === charCodes.slash && this.endsWith(charCodes.slash))\n ) {\n this._space();\n }\n\n this._maybeAddAuxComment();\n this._append(str, false);\n\n this._endsWithWord = true;\n }\n\n /**\n * Writes a number token so that we can validate if it is an integer.\n */\n\n number(str: string): void {\n this.word(str);\n\n // Integer tokens need special handling because they cannot have '.'s inserted\n // immediately after them.\n this._endsWithInteger =\n Number.isInteger(+str) &&\n !NON_DECIMAL_LITERAL.test(str) &&\n !SCIENTIFIC_NOTATION.test(str) &&\n !ZERO_DECIMAL_INTEGER.test(str) &&\n str.charCodeAt(str.length - 1) !== charCodes.dot;\n }\n\n /**\n * Writes a simple token.\n */\n\n token(str: string, maybeNewline = false): void {\n // space is mandatory to avoid outputting ` 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 = { + Accessor: "Deprecated. Will be removed in Babel 8.", + 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`. For example, a `StaticBlock` is a `FunctionParent` but not `Function`.", + 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.", + Miscellaneous: + "A cover of non-standard AST types that are sometimes useful for development.", + 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).", + Standardized: + "A cover of AST nodes which are part of an official ECMAScript specification.", + 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.", + TypeScript: "A cover of AST nodes defined for TypeScript.", + 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..06cd388 --- /dev/null +++ b/node_modules/@babel/types/scripts/generators/flow.js @@ -0,0 +1,260 @@ +import * as 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..7701047 --- /dev/null +++ b/node_modules/@babel/types/scripts/generators/typescript-legacy.js @@ -0,0 +1,369 @@ +import * as 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..f7ac23a --- /dev/null +++ b/node_modules/@babel/types/scripts/generators/validators.js @@ -0,0 +1,91 @@ +import { + DEPRECATED_KEYS, + FLIPPED_ALIAS_KEYS, + NODE_FIELDS, + PLACEHOLDERS, + PLACEHOLDERS_FLIPPED_ALIAS, + VISITOR_KEYS, +} from "../../lib/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 (PLACEHOLDERS.includes(type) && has(FLIPPED_ALIAS_KEYS, type)) { + placeholderTypes.push(type); + } + if (has(PLACEHOLDERS_FLIPPED_ALIAS, type)) { + placeholderTypes.push(...PLACEHOLDERS_FLIPPED_ALIAS[type]); + } + if (placeholderTypes.length > 0) { + placeholderSource = + ' || nodeType === "Placeholder" && (' + + joinComparisons( + placeholderTypes, + "(node as t.Placeholder).expectedNode" + ) + + ")"; + } + + const result = + NODE_FIELDS[type] || 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(VISITOR_KEYS).forEach(type => { + output += addIsHelper(type); + }); + + Object.keys(FLIPPED_ALIAS_KEYS).forEach(type => { + output += addIsHelper(type, FLIPPED_ALIAS_KEYS[type]); + }); + + Object.keys(DEPRECATED_KEYS).forEach(type => { + const newType = 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..a3da470 --- /dev/null +++ b/node_modules/@babel/types/scripts/utils/stringifyValidator.js @@ -0,0 +1,69 @@ +export default function stringifyValidator(validator, nodePrefix) { + if (validator === undefined) { + return "any"; + } + + if (validator.each) { + return `Array<${stringifyValidator(validator.each, nodePrefix)}>`; + } + + if (validator.chainOf) { + const ret = stringifyValidator(validator.chainOf[1], nodePrefix); + return Array.isArray(ret) && ret.length === 1 && ret[0] === "any" + ? stringifyValidator(validator.chainOf[0], nodePrefix) + : ret; + } + + 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"). + */ +export 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/@bcoe/v8-coverage/.editorconfig b/node_modules/@bcoe/v8-coverage/.editorconfig new file mode 100644 index 0000000..86a63dc --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true diff --git a/node_modules/@bcoe/v8-coverage/.gitattributes b/node_modules/@bcoe/v8-coverage/.gitattributes new file mode 100644 index 0000000..4b2c1a2 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/.gitattributes @@ -0,0 +1,2 @@ +# Enforce `lf` for text files (even on Windows) +text eol=lf diff --git a/node_modules/@bcoe/v8-coverage/CHANGELOG.md b/node_modules/@bcoe/v8-coverage/CHANGELOG.md new file mode 100644 index 0000000..7300dec --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/CHANGELOG.md @@ -0,0 +1,250 @@ +## Next + +- **[Breaking change]** Replace `OutModules` enum by custom compiler option `mjsModule`. +- **[Breaking change]** Drop support for Pug, Sass, Angular & Webpack. +- **[Feature]** Expose custom registries for each target. +- **[Feature]** Add `dist.tscOptions` for `lib` target to override options for + distribution builds. +- **[Feature]** Native ESM tests with mocha. +- **[Fix]** Disable deprecated TsLint rules from the default config +- **[Fix]** Remove use of experimental `fs/promises` module. +- **[Internal]** Fix continuous deployment script (stop confusing PRs to master + with push to master) +- **[Internal]** Update dependencies +- **[Internal]** Fix deprecated Mocha types. + +## 0.17.1 (2017-05-03) + +- **[Fix]** Update dependencies, remove `std/esm` warning. + +## 0.17.0 (2017-04-22) + +- **[Breaking change]** Update dependencies. Use `esm` instead of `@std/esm`, update Typescript to `2.8.3`. +- **[Fix]** Fix Node processes spawn on Windows (Mocha, Nyc) + +## 0.16.2 (2017-02-07) + +- **[Fix]** Fix Typedoc generation: use `tsconfig.json` generated for the lib. +- **[Fix]** Write source map for `.mjs` files +- **[Fix]** Copy sources to `_src` when publishing a lib (#87). +- **[Internal]** Restore continuous deployment of documentation. + +## 0.16.1 (2017-01-20) + +- **[Feature]** Support `mocha` tests on `.mjs` files (using `@std/esm`). Enabled by default + if `outModules` is configured to emit `.mjs`. **You currently need to add + `"@std/esm": {"esm": "cjs"}` to your `package.json`.** + +## 0.16.0 (2017-01-09) + +- **[Breaking change]** Enable `allowSyntheticDefaultImports` and `esModuleInterop` by default +- **[Fix]** Allow deep module imports in default Tslint rules +- **[Fix]** Drop dependency on deprecated `gulp-util` +- **[Internal]** Replace most custom typings by types from `@types` + +## 0.15.8 (2017-12-05) + +- **[Fix]** Exit with non-zero code if command tested with coverage fails +- **[Fix]** Solve duplicated error message when using the `run` mocha task. +- **[Fix]** Exit with non-zero code when building scripts fails. + +## 0.15.7 (2017-11-29) + +- **[Feature]** Add `coverage` task to `mocha` target, use it for the default task + +## 0.15.6 (2017-11-29) + +- **[Fix]** Fix path to source in source maps. +- **[Fix]** Disable `number-literal-format` in default Tslint rules. It enforced uppercase for hex. +- **[Internal]** Enable integration with Greenkeeper. +- **[Internal]** Enable integration with Codecov +- **[Internal]** Enable code coverage + +## 0.15.5 (2017-11-10) + +- **[Feature]** Enable the following TsLint rules: `no-duplicate-switch-case`, `no-implicit-dependencies`, + `no-return-await` +- **[Internal]** Update self-dependency `0.15.4`, this restores the README on _npm_ +- **[Internal]** Add homepage and author fields to package.json + +## 0.15.4 (2017-11-10) + +- **[Fix]** Add support for custom additional copy for distribution builds. [#49](https://github.com/demurgos/turbo-gulp/issues/49) +- **[Internal]** Update self-dependency to `turbo-gulp` +- **[Internal]** Add link to license in `README.md` + +## 0.15.3 (2017-11-09) + +**Rename to `turbo-gulp`**. This package was previously named `demurgos-web-build-tools`. +This version is fully compatible: you can just change the name of your dependency. + +## 0.15.2 (2017-11-09) + +**The package is prepared to be renamed `turbo-gulp`.** +This is the last version released as `demurgos-web-build-tools`. + +- **[Feature]** Add support for watch mode for library targets. +- **[Fix]** Disable experimental support for `*.mjs` by default. +- **[Fix]** Do not emit duplicate TS errors + +## 0.15.1 (2017-10-19) + +- **[Feature]** Add experimental support for `*.mjs` files +- **[Fix]** Fix support of releases from Continuous Deployment using Travis. + +## 0.15.0 (2017-10-18) + +- **[Fix]** Add error handling for git deployment. +- **[Internal]** Enable continuous deployment of the `master` branch. + +## 0.15.0-beta.11 (2017-08-29) + +- **[Feature]** Add `LibTarget.dist.copySrc` option to disable copy of source files to the dist directory. + This allows to prevent issues with missing custom typings. +- **[Fix]** Mark `deploy` property of `LibTarget.typedoc` as optional. +- **[Internal]** Update self-dependency to `v0.15.0-beta.10`. + +## 0.15.0-beta.10 (2017-08-28) + +- **[Breaking]** Update Tslint rules to use `tslint@5.7.0`. +- **[Fix]** Set `allowJs` to false in default TSC options. +- **[Fix]** Do not pipe output of git commands to stdout. +- **[Internal]** Update self-dependency to `v0.15.0-beta.9`. + +## 0.15.0-beta.9 (2017-08-28) + +- **[Breaking]** Drop old-style `test` target. +- **[Breaking]** Drop old-style `node` target. +- **[Feature]** Add `mocha` target to run tests in `spec.ts` files. +- **[Feature]** Add `node` target to build and run top-level Node applications. +- **[Feature]** Provide `generateNodeTasks`, `generateLibTasks` and `generateMochaTasks` functions. + They create the tasks but do not register them. +- **[Fix]** Run `clean` before `dist`, if defined. +- **[Fix]** Run `dist` before `publish`. + +## 0.15.0-beta.8 (2017-08-26) + +- **[Fix]** Remove auth token and registry options for `:dist:publish`. It is better served + by configuring the environment appropriately. + +## 0.15.0-beta.7 (2017-08-26) + +- **[Feature]** Add `clean` task to `lib` targets. +- **[Fix]** Ensure that `gitHead` is defined when publishing a package to npm. + +## 0.15.0-beta.6 (2017-08-22) + +- **[Feature]** Add support for Typedoc deployment to a remote git branch (such as `gh-pages`) +- **[Feature]** Add support for `copy` tasks in new library target. +- **[Fix]** Resolve absolute paths when compiling scripts with custom typings. + +## 0.15.0-beta.5 (2017-08-14) + +- **[Fix]** Fix package entry for the main module. + +## 0.15.0-beta.4 (2017-08-14) + +- **[Breaking]** Drop ES5 build exposed to browsers with the `browser` field in `package.json`. +- **[Feature]** Introduce first new-style target (`LibTarget`). it supports typedoc generation, dev builds and + simple distribution. + +## 0.15.0-beta.3 (2017-08-11) + +- **[Breaking]** Update default lib target to use target-specific `srcDir`. +- **[Feature]** Allow to complete `srcDir` in target. +- **[Feature]** Add experimental library distribution supporting deep requires. + +## 0.15.0-beta.2 (2017-08-10) + +- **[Fix]** Default to CommonJS for project tsconfig.json +- **[Fix]** Add Typescript configuration for default project. +- **[Internal]** Update self-dependency to `0.15.0-beta.1`. + +## 0.15.0-beta.1 (2017-08-09) + +- **[Feature]** Support typed TSLint rules. +- **[Internal]** Update gulpfile.ts to use build tools `0.15.0-beta.0`. +- **[Fix]** Fix regressions caused by `0.15.0-beta.0` (missing type definition). + +## 0.15.0-beta.0 (2017-08-09) + +- **[Breaking]** Expose option interfaces directly in the main module instead of the `config` namespace. +- **[Breaking]** Rename `DEFAULT_PROJECT_OPTIONS` to `DEFAULT_PROJECT`. +- **[Feature]** Emit project-wide `tsconfig.json`. +- **[Internal]** Convert gulpfile to Typescript, use `ts-node` to run it. +- **[Internal]** Update dependencies + +## 0.14.3 (2017-07-16) + +- **[Feature]** Add `:lint:fix` project task to fix some lint errors. + +## 0.14.2 (2017-07-10) + +- **[Internal]** Update dependencies: add `package-lock.json` and update `tslint`. + +## 0.14.1 (2017-06-17) + +- **[Internal]** Update dependencies. +- **[Internal]** Drop dependency on _Bluebird_. +- **[Internal]** Drop dependency on _typings_. + +## 0.14.0 (2017-05-10) + +- **[Breaking]** Enforce trailing commas by default for multiline objects +- **[Feature]** Allow bump from either `master` or a branch with the same name as the tag (exampel: `v1.2.3`) +- **[Feature]** Support TSLint 8, allow to extend the default rules +- **[Patch]** Allow mergeable namespaces + +# 0.13.1 + +- **[Patch]** Allow namespaces in the default TS-Lint config + +# 0.13.0 + +- **[Breaking]** Major overhaul of the angular target. The server build no longer depends on the client. +- **[Breaking]** Update to `gulp@4` (from `gulp@3`) +- **[Breaking]** Update to `tslint@7` (from `tslint@6`), add stricter default rules +- **[Breaking]** Update signature of targetGenerators and project tasks: it only uses + `ProjectOptions` and `Target` now, the additional options are embedded in those two objects. +- **[Breaking]** Remove `:install`, `:instal:npm` and `:install:typings`. Use the `prepare` script in + your `package.json` file instead. +- Add `:tslint.json` project task to generate configuration for `tslint` +- Add first class support for processing of `pug` and `sass` files, similar to `copy` +- Implement end-to-end tests +- Enable `emitDecoratorMetadata` in default typescript options. +- Allow configuration of `:lint` with the `tslintOptions` property of the project configuration. +- Add `:watch` tasks for incremental builds. + +# 0.12.3 + +- Support `templateUrl` and `styleUrls` in angular modules. + +# 0.12.2 + +- Add `:build:copy` task. It copies user-defined files. + +# 0.12.1 + +- Fix `:watch` task. + +# 0.12.0 + +- **[Breaking]**: Change naming convention for tasks. The names primary part is + the target, then the action (`lib:build` instead of `build:lib`) to group + the tasks per target. +- **[Breaking]**: Use `typeRoots` instead of `definitions` in configuration to + specify Typescript definition files. +- Generate `tsconfig.json` file (mainly for editors) +- Implement the `test` target to run unit-tests with `mocha`. + +# 0.11.2 + +- Target `angular`: Add `build::assets:sass` for `.scss` files (Sassy CSS) + +# 0.11.1 + +- Rename project to `web-build-tools` (`demurgos-web-build-tools` on _npm_) +- Target `angular`: Add `build::assets`, `build::pug` and `build::static`. +- Update `gulp-typescript`: solve error message during compilation +- Targets `node` and `angular`: `build::scripts` now include in-lined source maps +- Target `node`: `watch:` to support incremental builds diff --git a/node_modules/@bcoe/v8-coverage/LICENSE.md b/node_modules/@bcoe/v8-coverage/LICENSE.md new file mode 100644 index 0000000..d588b5c --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright © 2015-2017 Charles Samborski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@bcoe/v8-coverage/LICENSE.txt b/node_modules/@bcoe/v8-coverage/LICENSE.txt new file mode 100644 index 0000000..629264e --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2017, 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/@bcoe/v8-coverage/README.md b/node_modules/@bcoe/v8-coverage/README.md new file mode 100644 index 0000000..eea761b --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/README.md @@ -0,0 +1,11 @@ +# V8 Coverage + +[![npm](https://img.shields.io/npm/v/@c88/v8-coverage.svg?maxAge=2592000)](https://www.npmjs.com/package/@c88/v8-coverage) +[![GitHub repository](https://img.shields.io/badge/Github-demurgos%2Fv8--coverage-blue.svg)](https://github.com/demurgos/v8-coverage) +[![Build status (Travis)](https://img.shields.io/travis/demurgos/v8-coverage/master.svg?maxAge=2592000)](https://travis-ci.org/demurgos/v8-coverage) +[![Build status (AppVeyor)](https://ci.appveyor.com/api/projects/status/qgcbdffyb9e09d0e?svg=true)](https://ci.appveyor.com/project/demurgos/v8-coverage) +[![Codecov](https://codecov.io/gh/demurgos/v8-coverage/branch/master/graph/badge.svg)](https://codecov.io/gh/demurgos/v8-coverage) + +## License + +[MIT License](./LICENSE.md) diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/CHANGELOG.md b/node_modules/@bcoe/v8-coverage/dist/lib/CHANGELOG.md new file mode 100644 index 0000000..7300dec --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/CHANGELOG.md @@ -0,0 +1,250 @@ +## Next + +- **[Breaking change]** Replace `OutModules` enum by custom compiler option `mjsModule`. +- **[Breaking change]** Drop support for Pug, Sass, Angular & Webpack. +- **[Feature]** Expose custom registries for each target. +- **[Feature]** Add `dist.tscOptions` for `lib` target to override options for + distribution builds. +- **[Feature]** Native ESM tests with mocha. +- **[Fix]** Disable deprecated TsLint rules from the default config +- **[Fix]** Remove use of experimental `fs/promises` module. +- **[Internal]** Fix continuous deployment script (stop confusing PRs to master + with push to master) +- **[Internal]** Update dependencies +- **[Internal]** Fix deprecated Mocha types. + +## 0.17.1 (2017-05-03) + +- **[Fix]** Update dependencies, remove `std/esm` warning. + +## 0.17.0 (2017-04-22) + +- **[Breaking change]** Update dependencies. Use `esm` instead of `@std/esm`, update Typescript to `2.8.3`. +- **[Fix]** Fix Node processes spawn on Windows (Mocha, Nyc) + +## 0.16.2 (2017-02-07) + +- **[Fix]** Fix Typedoc generation: use `tsconfig.json` generated for the lib. +- **[Fix]** Write source map for `.mjs` files +- **[Fix]** Copy sources to `_src` when publishing a lib (#87). +- **[Internal]** Restore continuous deployment of documentation. + +## 0.16.1 (2017-01-20) + +- **[Feature]** Support `mocha` tests on `.mjs` files (using `@std/esm`). Enabled by default + if `outModules` is configured to emit `.mjs`. **You currently need to add + `"@std/esm": {"esm": "cjs"}` to your `package.json`.** + +## 0.16.0 (2017-01-09) + +- **[Breaking change]** Enable `allowSyntheticDefaultImports` and `esModuleInterop` by default +- **[Fix]** Allow deep module imports in default Tslint rules +- **[Fix]** Drop dependency on deprecated `gulp-util` +- **[Internal]** Replace most custom typings by types from `@types` + +## 0.15.8 (2017-12-05) + +- **[Fix]** Exit with non-zero code if command tested with coverage fails +- **[Fix]** Solve duplicated error message when using the `run` mocha task. +- **[Fix]** Exit with non-zero code when building scripts fails. + +## 0.15.7 (2017-11-29) + +- **[Feature]** Add `coverage` task to `mocha` target, use it for the default task + +## 0.15.6 (2017-11-29) + +- **[Fix]** Fix path to source in source maps. +- **[Fix]** Disable `number-literal-format` in default Tslint rules. It enforced uppercase for hex. +- **[Internal]** Enable integration with Greenkeeper. +- **[Internal]** Enable integration with Codecov +- **[Internal]** Enable code coverage + +## 0.15.5 (2017-11-10) + +- **[Feature]** Enable the following TsLint rules: `no-duplicate-switch-case`, `no-implicit-dependencies`, + `no-return-await` +- **[Internal]** Update self-dependency `0.15.4`, this restores the README on _npm_ +- **[Internal]** Add homepage and author fields to package.json + +## 0.15.4 (2017-11-10) + +- **[Fix]** Add support for custom additional copy for distribution builds. [#49](https://github.com/demurgos/turbo-gulp/issues/49) +- **[Internal]** Update self-dependency to `turbo-gulp` +- **[Internal]** Add link to license in `README.md` + +## 0.15.3 (2017-11-09) + +**Rename to `turbo-gulp`**. This package was previously named `demurgos-web-build-tools`. +This version is fully compatible: you can just change the name of your dependency. + +## 0.15.2 (2017-11-09) + +**The package is prepared to be renamed `turbo-gulp`.** +This is the last version released as `demurgos-web-build-tools`. + +- **[Feature]** Add support for watch mode for library targets. +- **[Fix]** Disable experimental support for `*.mjs` by default. +- **[Fix]** Do not emit duplicate TS errors + +## 0.15.1 (2017-10-19) + +- **[Feature]** Add experimental support for `*.mjs` files +- **[Fix]** Fix support of releases from Continuous Deployment using Travis. + +## 0.15.0 (2017-10-18) + +- **[Fix]** Add error handling for git deployment. +- **[Internal]** Enable continuous deployment of the `master` branch. + +## 0.15.0-beta.11 (2017-08-29) + +- **[Feature]** Add `LibTarget.dist.copySrc` option to disable copy of source files to the dist directory. + This allows to prevent issues with missing custom typings. +- **[Fix]** Mark `deploy` property of `LibTarget.typedoc` as optional. +- **[Internal]** Update self-dependency to `v0.15.0-beta.10`. + +## 0.15.0-beta.10 (2017-08-28) + +- **[Breaking]** Update Tslint rules to use `tslint@5.7.0`. +- **[Fix]** Set `allowJs` to false in default TSC options. +- **[Fix]** Do not pipe output of git commands to stdout. +- **[Internal]** Update self-dependency to `v0.15.0-beta.9`. + +## 0.15.0-beta.9 (2017-08-28) + +- **[Breaking]** Drop old-style `test` target. +- **[Breaking]** Drop old-style `node` target. +- **[Feature]** Add `mocha` target to run tests in `spec.ts` files. +- **[Feature]** Add `node` target to build and run top-level Node applications. +- **[Feature]** Provide `generateNodeTasks`, `generateLibTasks` and `generateMochaTasks` functions. + They create the tasks but do not register them. +- **[Fix]** Run `clean` before `dist`, if defined. +- **[Fix]** Run `dist` before `publish`. + +## 0.15.0-beta.8 (2017-08-26) + +- **[Fix]** Remove auth token and registry options for `:dist:publish`. It is better served + by configuring the environment appropriately. + +## 0.15.0-beta.7 (2017-08-26) + +- **[Feature]** Add `clean` task to `lib` targets. +- **[Fix]** Ensure that `gitHead` is defined when publishing a package to npm. + +## 0.15.0-beta.6 (2017-08-22) + +- **[Feature]** Add support for Typedoc deployment to a remote git branch (such as `gh-pages`) +- **[Feature]** Add support for `copy` tasks in new library target. +- **[Fix]** Resolve absolute paths when compiling scripts with custom typings. + +## 0.15.0-beta.5 (2017-08-14) + +- **[Fix]** Fix package entry for the main module. + +## 0.15.0-beta.4 (2017-08-14) + +- **[Breaking]** Drop ES5 build exposed to browsers with the `browser` field in `package.json`. +- **[Feature]** Introduce first new-style target (`LibTarget`). it supports typedoc generation, dev builds and + simple distribution. + +## 0.15.0-beta.3 (2017-08-11) + +- **[Breaking]** Update default lib target to use target-specific `srcDir`. +- **[Feature]** Allow to complete `srcDir` in target. +- **[Feature]** Add experimental library distribution supporting deep requires. + +## 0.15.0-beta.2 (2017-08-10) + +- **[Fix]** Default to CommonJS for project tsconfig.json +- **[Fix]** Add Typescript configuration for default project. +- **[Internal]** Update self-dependency to `0.15.0-beta.1`. + +## 0.15.0-beta.1 (2017-08-09) + +- **[Feature]** Support typed TSLint rules. +- **[Internal]** Update gulpfile.ts to use build tools `0.15.0-beta.0`. +- **[Fix]** Fix regressions caused by `0.15.0-beta.0` (missing type definition). + +## 0.15.0-beta.0 (2017-08-09) + +- **[Breaking]** Expose option interfaces directly in the main module instead of the `config` namespace. +- **[Breaking]** Rename `DEFAULT_PROJECT_OPTIONS` to `DEFAULT_PROJECT`. +- **[Feature]** Emit project-wide `tsconfig.json`. +- **[Internal]** Convert gulpfile to Typescript, use `ts-node` to run it. +- **[Internal]** Update dependencies + +## 0.14.3 (2017-07-16) + +- **[Feature]** Add `:lint:fix` project task to fix some lint errors. + +## 0.14.2 (2017-07-10) + +- **[Internal]** Update dependencies: add `package-lock.json` and update `tslint`. + +## 0.14.1 (2017-06-17) + +- **[Internal]** Update dependencies. +- **[Internal]** Drop dependency on _Bluebird_. +- **[Internal]** Drop dependency on _typings_. + +## 0.14.0 (2017-05-10) + +- **[Breaking]** Enforce trailing commas by default for multiline objects +- **[Feature]** Allow bump from either `master` or a branch with the same name as the tag (exampel: `v1.2.3`) +- **[Feature]** Support TSLint 8, allow to extend the default rules +- **[Patch]** Allow mergeable namespaces + +# 0.13.1 + +- **[Patch]** Allow namespaces in the default TS-Lint config + +# 0.13.0 + +- **[Breaking]** Major overhaul of the angular target. The server build no longer depends on the client. +- **[Breaking]** Update to `gulp@4` (from `gulp@3`) +- **[Breaking]** Update to `tslint@7` (from `tslint@6`), add stricter default rules +- **[Breaking]** Update signature of targetGenerators and project tasks: it only uses + `ProjectOptions` and `Target` now, the additional options are embedded in those two objects. +- **[Breaking]** Remove `:install`, `:instal:npm` and `:install:typings`. Use the `prepare` script in + your `package.json` file instead. +- Add `:tslint.json` project task to generate configuration for `tslint` +- Add first class support for processing of `pug` and `sass` files, similar to `copy` +- Implement end-to-end tests +- Enable `emitDecoratorMetadata` in default typescript options. +- Allow configuration of `:lint` with the `tslintOptions` property of the project configuration. +- Add `:watch` tasks for incremental builds. + +# 0.12.3 + +- Support `templateUrl` and `styleUrls` in angular modules. + +# 0.12.2 + +- Add `:build:copy` task. It copies user-defined files. + +# 0.12.1 + +- Fix `:watch` task. + +# 0.12.0 + +- **[Breaking]**: Change naming convention for tasks. The names primary part is + the target, then the action (`lib:build` instead of `build:lib`) to group + the tasks per target. +- **[Breaking]**: Use `typeRoots` instead of `definitions` in configuration to + specify Typescript definition files. +- Generate `tsconfig.json` file (mainly for editors) +- Implement the `test` target to run unit-tests with `mocha`. + +# 0.11.2 + +- Target `angular`: Add `build::assets:sass` for `.scss` files (Sassy CSS) + +# 0.11.1 + +- Rename project to `web-build-tools` (`demurgos-web-build-tools` on _npm_) +- Target `angular`: Add `build::assets`, `build::pug` and `build::static`. +- Update `gulp-typescript`: solve error message during compilation +- Targets `node` and `angular`: `build::scripts` now include in-lined source maps +- Target `node`: `watch:` to support incremental builds diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/LICENSE.md b/node_modules/@bcoe/v8-coverage/dist/lib/LICENSE.md new file mode 100644 index 0000000..d588b5c --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright © 2015-2017 Charles Samborski + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@bcoe/v8-coverage/dist/lib/README.md b/node_modules/@bcoe/v8-coverage/dist/lib/README.md new file mode 100644 index 0000000..eea761b --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/README.md @@ -0,0 +1,11 @@ +# V8 Coverage + +[![npm](https://img.shields.io/npm/v/@c88/v8-coverage.svg?maxAge=2592000)](https://www.npmjs.com/package/@c88/v8-coverage) +[![GitHub repository](https://img.shields.io/badge/Github-demurgos%2Fv8--coverage-blue.svg)](https://github.com/demurgos/v8-coverage) +[![Build status (Travis)](https://img.shields.io/travis/demurgos/v8-coverage/master.svg?maxAge=2592000)](https://travis-ci.org/demurgos/v8-coverage) +[![Build status (AppVeyor)](https://ci.appveyor.com/api/projects/status/qgcbdffyb9e09d0e?svg=true)](https://ci.appveyor.com/project/demurgos/v8-coverage) +[![Codecov](https://codecov.io/gh/demurgos/v8-coverage/branch/master/graph/badge.svg)](https://codecov.io/gh/demurgos/v8-coverage) + +## License + +[MIT License](./LICENSE.md) diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/_src/ascii.ts b/node_modules/@bcoe/v8-coverage/dist/lib/_src/ascii.ts new file mode 100644 index 0000000..5a52b91 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/_src/ascii.ts @@ -0,0 +1,146 @@ +import { compareRangeCovs } from "./compare"; +import { RangeCov } from "./types"; + +interface ReadonlyRangeTree { + readonly start: number; + readonly end: number; + readonly count: number; + readonly children: ReadonlyRangeTree[]; +} + +export function emitForest(trees: ReadonlyArray): string { + return emitForestLines(trees).join("\n"); +} + +export function emitForestLines(trees: ReadonlyArray): string[] { + const colMap: Map = getColMap(trees); + const header: string = emitOffsets(colMap); + return [header, ...trees.map(tree => emitTree(tree, colMap).join("\n"))]; +} + +function getColMap(trees: Iterable): Map { + const eventSet: Set = new Set(); + for (const tree of trees) { + const stack: ReadonlyRangeTree[] = [tree]; + while (stack.length > 0) { + const cur: ReadonlyRangeTree = stack.pop()!; + eventSet.add(cur.start); + eventSet.add(cur.end); + for (const child of cur.children) { + stack.push(child); + } + } + } + const events: number[] = [...eventSet]; + events.sort((a, b) => a - b); + let maxDigits: number = 1; + for (const event of events) { + maxDigits = Math.max(maxDigits, event.toString(10).length); + } + const colWidth: number = maxDigits + 3; + const colMap: Map = new Map(); + for (const [i, event] of events.entries()) { + colMap.set(event, i * colWidth); + } + return colMap; +} + +function emitTree(tree: ReadonlyRangeTree, colMap: Map): string[] { + const layers: ReadonlyRangeTree[][] = []; + let nextLayer: ReadonlyRangeTree[] = [tree]; + while (nextLayer.length > 0) { + const layer: ReadonlyRangeTree[] = nextLayer; + layers.push(layer); + nextLayer = []; + for (const node of layer) { + for (const child of node.children) { + nextLayer.push(child); + } + } + } + return layers.map(layer => emitTreeLayer(layer, colMap)); +} + +export function parseFunctionRanges(text: string, offsetMap: Map): RangeCov[] { + const result: RangeCov[] = []; + for (const line of text.split("\n")) { + for (const range of parseTreeLayer(line, offsetMap)) { + result.push(range); + } + } + result.sort(compareRangeCovs); + return result; +} + +/** + * + * @param layer Sorted list of disjoint trees. + * @param colMap + */ +function emitTreeLayer(layer: ReadonlyRangeTree[], colMap: Map): string { + const line: string[] = []; + let curIdx: number = 0; + for (const {start, end, count} of layer) { + const startIdx: number = colMap.get(start)!; + const endIdx: number = colMap.get(end)!; + if (startIdx > curIdx) { + line.push(" ".repeat(startIdx - curIdx)); + } + line.push(emitRange(count, endIdx - startIdx)); + curIdx = endIdx; + } + return line.join(""); +} + +function parseTreeLayer(text: string, offsetMap: Map): RangeCov[] { + const result: RangeCov[] = []; + const regex: RegExp = /\[(\d+)-*\)/gs; + while (true) { + const match: RegExpMatchArray | null = regex.exec(text); + if (match === null) { + break; + } + const startIdx: number = match.index!; + const endIdx: number = startIdx + match[0].length; + const count: number = parseInt(match[1], 10); + const startOffset: number | undefined = offsetMap.get(startIdx); + const endOffset: number | undefined = offsetMap.get(endIdx); + if (startOffset === undefined || endOffset === undefined) { + throw new Error(`Invalid offsets for: ${JSON.stringify(text)}`); + } + result.push({startOffset, endOffset, count}); + } + return result; +} + +function emitRange(count: number, len: number): string { + const rangeStart: string = `[${count.toString(10)}`; + const rangeEnd: string = ")"; + const hyphensLen: number = len - (rangeStart.length + rangeEnd.length); + const hyphens: string = "-".repeat(Math.max(0, hyphensLen)); + return `${rangeStart}${hyphens}${rangeEnd}`; +} + +function emitOffsets(colMap: Map): string { + let line: string = ""; + for (const [event, col] of colMap) { + if (line.length < col) { + line += " ".repeat(col - line.length); + } + line += event.toString(10); + } + return line; +} + +export function parseOffsets(text: string): Map { + const result: Map = new Map(); + const regex: RegExp = /\d+/gs; + while (true) { + const match: RegExpExecArray | null = regex.exec(text); + if (match === null) { + break; + } + result.set(match.index, parseInt(match[0], 10)); + } + return result; +} diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/_src/clone.ts b/node_modules/@bcoe/v8-coverage/dist/lib/_src/clone.ts new file mode 100644 index 0000000..1a91019 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/_src/clone.ts @@ -0,0 +1,70 @@ +import { FunctionCov, ProcessCov, RangeCov, ScriptCov } from "./types"; + +/** + * Creates a deep copy of a process coverage. + * + * @param processCov Process coverage to clone. + * @return Cloned process coverage. + */ +export function cloneProcessCov(processCov: Readonly): ProcessCov { + const result: ScriptCov[] = []; + for (const scriptCov of processCov.result) { + result.push(cloneScriptCov(scriptCov)); + } + + return { + result, + }; +} + +/** + * Creates a deep copy of a script coverage. + * + * @param scriptCov Script coverage to clone. + * @return Cloned script coverage. + */ +export function cloneScriptCov(scriptCov: Readonly): ScriptCov { + const functions: FunctionCov[] = []; + for (const functionCov of scriptCov.functions) { + functions.push(cloneFunctionCov(functionCov)); + } + + return { + scriptId: scriptCov.scriptId, + url: scriptCov.url, + functions, + }; +} + +/** + * Creates a deep copy of a function coverage. + * + * @param functionCov Function coverage to clone. + * @return Cloned function coverage. + */ +export function cloneFunctionCov(functionCov: Readonly): FunctionCov { + const ranges: RangeCov[] = []; + for (const rangeCov of functionCov.ranges) { + ranges.push(cloneRangeCov(rangeCov)); + } + + return { + functionName: functionCov.functionName, + ranges, + isBlockCoverage: functionCov.isBlockCoverage, + }; +} + +/** + * Creates a deep copy of a function coverage. + * + * @param rangeCov Range coverage to clone. + * @return Cloned range coverage. + */ +export function cloneRangeCov(rangeCov: Readonly): RangeCov { + return { + startOffset: rangeCov.startOffset, + endOffset: rangeCov.endOffset, + count: rangeCov.count, + }; +} diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/_src/compare.ts b/node_modules/@bcoe/v8-coverage/dist/lib/_src/compare.ts new file mode 100644 index 0000000..8f5614c --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/_src/compare.ts @@ -0,0 +1,40 @@ +import { FunctionCov, RangeCov, ScriptCov } from "./types"; + +/** + * Compares two script coverages. + * + * The result corresponds to the comparison of their `url` value (alphabetical sort). + */ +export function compareScriptCovs(a: Readonly, b: Readonly): number { + if (a.url === b.url) { + return 0; + } else if (a.url < b.url) { + return -1; + } else { + return 1; + } +} + +/** + * Compares two function coverages. + * + * The result corresponds to the comparison of the root ranges. + */ +export function compareFunctionCovs(a: Readonly, b: Readonly): number { + return compareRangeCovs(a.ranges[0], b.ranges[0]); +} + +/** + * Compares two range coverages. + * + * The ranges are first ordered by ascending `startOffset` and then by + * descending `endOffset`. + * This corresponds to a pre-order tree traversal. + */ +export function compareRangeCovs(a: Readonly, b: Readonly): number { + if (a.startOffset !== b.startOffset) { + return a.startOffset - b.startOffset; + } else { + return b.endOffset - a.endOffset; + } +} diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/_src/index.ts b/node_modules/@bcoe/v8-coverage/dist/lib/_src/index.ts new file mode 100644 index 0000000..f92bdf3 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/_src/index.ts @@ -0,0 +1,6 @@ +export { emitForest, emitForestLines, parseFunctionRanges, parseOffsets } from "./ascii"; +export { cloneFunctionCov, cloneProcessCov, cloneScriptCov, cloneRangeCov } from "./clone"; +export { compareScriptCovs, compareFunctionCovs, compareRangeCovs } from "./compare"; +export { mergeFunctionCovs, mergeProcessCovs, mergeScriptCovs } from "./merge"; +export { RangeTree } from "./range-tree"; +export { ProcessCov, ScriptCov, FunctionCov, RangeCov } from "./types"; diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/_src/merge.ts b/node_modules/@bcoe/v8-coverage/dist/lib/_src/merge.ts new file mode 100644 index 0000000..64d1918 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/_src/merge.ts @@ -0,0 +1,343 @@ +import { + deepNormalizeScriptCov, + normalizeFunctionCov, + normalizeProcessCov, + normalizeRangeTree, + normalizeScriptCov, +} from "./normalize"; +import { RangeTree } from "./range-tree"; +import { FunctionCov, ProcessCov, Range, RangeCov, ScriptCov } from "./types"; + +/** + * Merges a list of process coverages. + * + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param processCovs Process coverages to merge. + * @return Merged process coverage. + */ +export function mergeProcessCovs(processCovs: ReadonlyArray): ProcessCov { + if (processCovs.length === 0) { + return {result: []}; + } + + const urlToScripts: Map = new Map(); + for (const processCov of processCovs) { + for (const scriptCov of processCov.result) { + let scriptCovs: ScriptCov[] | undefined = urlToScripts.get(scriptCov.url); + if (scriptCovs === undefined) { + scriptCovs = []; + urlToScripts.set(scriptCov.url, scriptCovs); + } + scriptCovs.push(scriptCov); + } + } + + const result: ScriptCov[] = []; + for (const scripts of urlToScripts.values()) { + // assert: `scripts.length > 0` + result.push(mergeScriptCovs(scripts)!); + } + const merged: ProcessCov = {result}; + + normalizeProcessCov(merged); + return merged; +} + +/** + * Merges a list of matching script coverages. + * + * Scripts are matching if they have the same `url`. + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param scriptCovs Process coverages to merge. + * @return Merged script coverage, or `undefined` if the input list was empty. + */ +export function mergeScriptCovs(scriptCovs: ReadonlyArray): ScriptCov | undefined { + if (scriptCovs.length === 0) { + return undefined; + } else if (scriptCovs.length === 1) { + const merged: ScriptCov = scriptCovs[0]; + deepNormalizeScriptCov(merged); + return merged; + } + + const first: ScriptCov = scriptCovs[0]; + const scriptId: string = first.scriptId; + const url: string = first.url; + + const rangeToFuncs: Map = new Map(); + for (const scriptCov of scriptCovs) { + for (const funcCov of scriptCov.functions) { + const rootRange: string = stringifyFunctionRootRange(funcCov); + let funcCovs: FunctionCov[] | undefined = rangeToFuncs.get(rootRange); + + if (funcCovs === undefined || + // if the entry in rangeToFuncs is function-level granularity and + // the new coverage is block-level, prefer block-level. + (!funcCovs[0].isBlockCoverage && funcCov.isBlockCoverage)) { + funcCovs = []; + rangeToFuncs.set(rootRange, funcCovs); + } else if (funcCovs[0].isBlockCoverage && !funcCov.isBlockCoverage) { + // if the entry in rangeToFuncs is block-level granularity, we should + // not append function level granularity. + continue; + } + funcCovs.push(funcCov); + } + } + + const functions: FunctionCov[] = []; + for (const funcCovs of rangeToFuncs.values()) { + // assert: `funcCovs.length > 0` + functions.push(mergeFunctionCovs(funcCovs)!); + } + + const merged: ScriptCov = {scriptId, url, functions}; + normalizeScriptCov(merged); + return merged; +} + +/** + * Returns a string representation of the root range of the function. + * + * This string can be used to match function with same root range. + * The string is derived from the start and end offsets of the root range of + * the function. + * This assumes that `ranges` is non-empty (true for valid function coverages). + * + * @param funcCov Function coverage with the range to stringify + * @internal + */ +function stringifyFunctionRootRange(funcCov: Readonly): string { + const rootRange: RangeCov = funcCov.ranges[0]; + return `${rootRange.startOffset.toString(10)};${rootRange.endOffset.toString(10)}`; +} + +/** + * Merges a list of matching function coverages. + * + * Functions are matching if their root ranges have the same span. + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param funcCovs Function coverages to merge. + * @return Merged function coverage, or `undefined` if the input list was empty. + */ +export function mergeFunctionCovs(funcCovs: ReadonlyArray): FunctionCov | undefined { + if (funcCovs.length === 0) { + return undefined; + } else if (funcCovs.length === 1) { + const merged: FunctionCov = funcCovs[0]; + normalizeFunctionCov(merged); + return merged; + } + + const functionName: string = funcCovs[0].functionName; + + const trees: RangeTree[] = []; + for (const funcCov of funcCovs) { + // assert: `fn.ranges.length > 0` + // assert: `fn.ranges` is sorted + trees.push(RangeTree.fromSortedRanges(funcCov.ranges)!); + } + + // assert: `trees.length > 0` + const mergedTree: RangeTree = mergeRangeTrees(trees)!; + normalizeRangeTree(mergedTree); + const ranges: RangeCov[] = mergedTree.toRanges(); + const isBlockCoverage: boolean = !(ranges.length === 1 && ranges[0].count === 0); + + const merged: FunctionCov = {functionName, ranges, isBlockCoverage}; + // assert: `merged` is normalized + return merged; +} + +/** + * @precondition Same `start` and `end` for all the trees + */ +function mergeRangeTrees(trees: ReadonlyArray): RangeTree | undefined { + if (trees.length <= 1) { + return trees[0]; + } + const first: RangeTree = trees[0]; + let delta: number = 0; + for (const tree of trees) { + delta += tree.delta; + } + const children: RangeTree[] = mergeRangeTreeChildren(trees); + return new RangeTree(first.start, first.end, delta, children); +} + +class RangeTreeWithParent { + readonly parentIndex: number; + readonly tree: RangeTree; + + constructor(parentIndex: number, tree: RangeTree) { + this.parentIndex = parentIndex; + this.tree = tree; + } +} + +class StartEvent { + readonly offset: number; + readonly trees: RangeTreeWithParent[]; + + constructor(offset: number, trees: RangeTreeWithParent[]) { + this.offset = offset; + this.trees = trees; + } + + static compare(a: StartEvent, b: StartEvent): number { + return a.offset - b.offset; + } +} + +class StartEventQueue { + private readonly queue: StartEvent[]; + private nextIndex: number; + private pendingOffset: number; + private pendingTrees: RangeTreeWithParent[] | undefined; + + private constructor(queue: StartEvent[]) { + this.queue = queue; + this.nextIndex = 0; + this.pendingOffset = 0; + this.pendingTrees = undefined; + } + + static fromParentTrees(parentTrees: ReadonlyArray): StartEventQueue { + const startToTrees: Map = new Map(); + for (const [parentIndex, parentTree] of parentTrees.entries()) { + for (const child of parentTree.children) { + let trees: RangeTreeWithParent[] | undefined = startToTrees.get(child.start); + if (trees === undefined) { + trees = []; + startToTrees.set(child.start, trees); + } + trees.push(new RangeTreeWithParent(parentIndex, child)); + } + } + const queue: StartEvent[] = []; + for (const [startOffset, trees] of startToTrees) { + queue.push(new StartEvent(startOffset, trees)); + } + queue.sort(StartEvent.compare); + return new StartEventQueue(queue); + } + + setPendingOffset(offset: number): void { + this.pendingOffset = offset; + } + + pushPendingTree(tree: RangeTreeWithParent): void { + if (this.pendingTrees === undefined) { + this.pendingTrees = []; + } + this.pendingTrees.push(tree); + } + + next(): StartEvent | undefined { + const pendingTrees: RangeTreeWithParent[] | undefined = this.pendingTrees; + const nextEvent: StartEvent | undefined = this.queue[this.nextIndex]; + if (pendingTrees === undefined) { + this.nextIndex++; + return nextEvent; + } else if (nextEvent === undefined) { + this.pendingTrees = undefined; + return new StartEvent(this.pendingOffset, pendingTrees); + } else { + if (this.pendingOffset < nextEvent.offset) { + this.pendingTrees = undefined; + return new StartEvent(this.pendingOffset, pendingTrees); + } else { + if (this.pendingOffset === nextEvent.offset) { + this.pendingTrees = undefined; + for (const tree of pendingTrees) { + nextEvent.trees.push(tree); + } + } + this.nextIndex++; + return nextEvent; + } + } + } +} + +function mergeRangeTreeChildren(parentTrees: ReadonlyArray): RangeTree[] { + const result: RangeTree[] = []; + const startEventQueue: StartEventQueue = StartEventQueue.fromParentTrees(parentTrees); + const parentToNested: Map = new Map(); + let openRange: Range | undefined; + + while (true) { + const event: StartEvent | undefined = startEventQueue.next(); + if (event === undefined) { + break; + } + + if (openRange !== undefined && openRange.end <= event.offset) { + result.push(nextChild(openRange, parentToNested)); + openRange = undefined; + } + + if (openRange === undefined) { + let openRangeEnd: number = event.offset + 1; + for (const {parentIndex, tree} of event.trees) { + openRangeEnd = Math.max(openRangeEnd, tree.end); + insertChild(parentToNested, parentIndex, tree); + } + startEventQueue.setPendingOffset(openRangeEnd); + openRange = {start: event.offset, end: openRangeEnd}; + } else { + for (const {parentIndex, tree} of event.trees) { + if (tree.end > openRange.end) { + const right: RangeTree = tree.split(openRange.end); + startEventQueue.pushPendingTree(new RangeTreeWithParent(parentIndex, right)); + } + insertChild(parentToNested, parentIndex, tree); + } + } + } + if (openRange !== undefined) { + result.push(nextChild(openRange, parentToNested)); + } + + return result; +} + +function insertChild(parentToNested: Map, parentIndex: number, tree: RangeTree): void { + let nested: RangeTree[] | undefined = parentToNested.get(parentIndex); + if (nested === undefined) { + nested = []; + parentToNested.set(parentIndex, nested); + } + nested.push(tree); +} + +function nextChild(openRange: Range, parentToNested: Map): RangeTree { + const matchingTrees: RangeTree[] = []; + + for (const nested of parentToNested.values()) { + if (nested.length === 1 && nested[0].start === openRange.start && nested[0].end === openRange.end) { + matchingTrees.push(nested[0]); + } else { + matchingTrees.push(new RangeTree( + openRange.start, + openRange.end, + 0, + nested, + )); + } + } + parentToNested.clear(); + return mergeRangeTrees(matchingTrees)!; +} diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/_src/normalize.ts b/node_modules/@bcoe/v8-coverage/dist/lib/_src/normalize.ts new file mode 100644 index 0000000..0269116 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/_src/normalize.ts @@ -0,0 +1,84 @@ +import { compareFunctionCovs, compareRangeCovs, compareScriptCovs } from "./compare"; +import { RangeTree } from "./range-tree"; +import { FunctionCov, ProcessCov, ScriptCov } from "./types"; + +/** + * Normalizes a process coverage. + * + * Sorts the scripts alphabetically by `url`. + * Reassigns script ids: the script at index `0` receives `"0"`, the script at + * index `1` receives `"1"` etc. + * This does not normalize the script coverages. + * + * @param processCov Process coverage to normalize. + */ +export function normalizeProcessCov(processCov: ProcessCov): void { + processCov.result.sort(compareScriptCovs); + for (const [scriptId, scriptCov] of processCov.result.entries()) { + scriptCov.scriptId = scriptId.toString(10); + } +} + +/** + * Normalizes a process coverage deeply. + * + * Normalizes the script coverages deeply, then normalizes the process coverage + * itself. + * + * @param processCov Process coverage to normalize. + */ +export function deepNormalizeProcessCov(processCov: ProcessCov): void { + for (const scriptCov of processCov.result) { + deepNormalizeScriptCov(scriptCov); + } + normalizeProcessCov(processCov); +} + +/** + * Normalizes a script coverage. + * + * Sorts the function by root range (pre-order sort). + * This does not normalize the function coverages. + * + * @param scriptCov Script coverage to normalize. + */ +export function normalizeScriptCov(scriptCov: ScriptCov): void { + scriptCov.functions.sort(compareFunctionCovs); +} + +/** + * Normalizes a script coverage deeply. + * + * Normalizes the function coverages deeply, then normalizes the script coverage + * itself. + * + * @param scriptCov Script coverage to normalize. + */ +export function deepNormalizeScriptCov(scriptCov: ScriptCov): void { + for (const funcCov of scriptCov.functions) { + normalizeFunctionCov(funcCov); + } + normalizeScriptCov(scriptCov); +} + +/** + * Normalizes a function coverage. + * + * Sorts the ranges (pre-order sort). + * TODO: Tree-based normalization of the ranges. + * + * @param funcCov Function coverage to normalize. + */ +export function normalizeFunctionCov(funcCov: FunctionCov): void { + funcCov.ranges.sort(compareRangeCovs); + const tree: RangeTree = RangeTree.fromSortedRanges(funcCov.ranges)!; + normalizeRangeTree(tree); + funcCov.ranges = tree.toRanges(); +} + +/** + * @internal + */ +export function normalizeRangeTree(tree: RangeTree): void { + tree.normalize(); +} diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/_src/range-tree.ts b/node_modules/@bcoe/v8-coverage/dist/lib/_src/range-tree.ts new file mode 100644 index 0000000..941ec82 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/_src/range-tree.ts @@ -0,0 +1,156 @@ +import { RangeCov } from "./types"; + +export class RangeTree { + start: number; + end: number; + delta: number; + children: RangeTree[]; + + constructor( + start: number, + end: number, + delta: number, + children: RangeTree[], + ) { + this.start = start; + this.end = end; + this.delta = delta; + this.children = children; + } + + /** + * @precodition `ranges` are well-formed and pre-order sorted + */ + static fromSortedRanges(ranges: ReadonlyArray): RangeTree | undefined { + let root: RangeTree | undefined; + // Stack of parent trees and parent counts. + const stack: [RangeTree, number][] = []; + for (const range of ranges) { + const node: RangeTree = new RangeTree(range.startOffset, range.endOffset, range.count, []); + if (root === undefined) { + root = node; + stack.push([node, range.count]); + continue; + } + let parent: RangeTree; + let parentCount: number; + while (true) { + [parent, parentCount] = stack[stack.length - 1]; + // assert: `top !== undefined` (the ranges are sorted) + if (range.startOffset < parent.end) { + break; + } else { + stack.pop(); + } + } + node.delta -= parentCount; + parent.children.push(node); + stack.push([node, range.count]); + } + return root; + } + + normalize(): void { + const children: RangeTree[] = []; + let curEnd: number; + let head: RangeTree | undefined; + const tail: RangeTree[] = []; + for (const child of this.children) { + if (head === undefined) { + head = child; + } else if (child.delta === head.delta && child.start === curEnd!) { + tail.push(child); + } else { + endChain(); + head = child; + } + curEnd = child.end; + } + if (head !== undefined) { + endChain(); + } + + if (children.length === 1) { + const child: RangeTree = children[0]; + if (child.start === this.start && child.end === this.end) { + this.delta += child.delta; + this.children = child.children; + // `.lazyCount` is zero for both (both are after normalization) + return; + } + } + + this.children = children; + + function endChain(): void { + if (tail.length !== 0) { + head!.end = tail[tail.length - 1].end; + for (const tailTree of tail) { + for (const subChild of tailTree.children) { + subChild.delta += tailTree.delta - head!.delta; + head!.children.push(subChild); + } + } + tail.length = 0; + } + head!.normalize(); + children.push(head!); + } + } + + /** + * @precondition `tree.start < value && value < tree.end` + * @return RangeTree Right part + */ + split(value: number): RangeTree { + let leftChildLen: number = this.children.length; + let mid: RangeTree | undefined; + + // TODO(perf): Binary search (check overhead) + for (let i: number = 0; i < this.children.length; i++) { + const child: RangeTree = this.children[i]; + if (child.start < value && value < child.end) { + mid = child.split(value); + leftChildLen = i + 1; + break; + } else if (child.start >= value) { + leftChildLen = i; + break; + } + } + + const rightLen: number = this.children.length - leftChildLen; + const rightChildren: RangeTree[] = this.children.splice(leftChildLen, rightLen); + if (mid !== undefined) { + rightChildren.unshift(mid); + } + const result: RangeTree = new RangeTree( + value, + this.end, + this.delta, + rightChildren, + ); + this.end = value; + return result; + } + + /** + * Get the range coverages corresponding to the tree. + * + * The ranges are pre-order sorted. + */ + toRanges(): RangeCov[] { + const ranges: RangeCov[] = []; + // Stack of parent trees and counts. + const stack: [RangeTree, number][] = [[this, 0]]; + while (stack.length > 0) { + const [cur, parentCount]: [RangeTree, number] = stack.pop()!; + const count: number = parentCount + cur.delta; + ranges.push({startOffset: cur.start, endOffset: cur.end, count}); + for (let i: number = cur.children.length - 1; i >= 0; i--) { + stack.push([cur.children[i], count]); + } + } + return ranges; + } +} diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/_src/types.ts b/node_modules/@bcoe/v8-coverage/dist/lib/_src/types.ts new file mode 100644 index 0000000..cc2cfc5 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/_src/types.ts @@ -0,0 +1,26 @@ +export interface ProcessCov { + result: ScriptCov[]; +} + +export interface ScriptCov { + scriptId: string; + url: string; + functions: FunctionCov[]; +} + +export interface FunctionCov { + functionName: string; + ranges: RangeCov[]; + isBlockCoverage: boolean; +} + +export interface Range { + readonly start: number; + readonly end: number; +} + +export interface RangeCov { + startOffset: number; + endOffset: number; + count: number; +} diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/ascii.d.ts b/node_modules/@bcoe/v8-coverage/dist/lib/ascii.d.ts new file mode 100644 index 0000000..a56836d --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/ascii.d.ts @@ -0,0 +1,12 @@ +import { RangeCov } from "./types"; +interface ReadonlyRangeTree { + readonly start: number; + readonly end: number; + readonly count: number; + readonly children: ReadonlyRangeTree[]; +} +export declare function emitForest(trees: ReadonlyArray): string; +export declare function emitForestLines(trees: ReadonlyArray): string[]; +export declare function parseFunctionRanges(text: string, offsetMap: Map): RangeCov[]; +export declare function parseOffsets(text: string): Map; +export {}; diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/ascii.js b/node_modules/@bcoe/v8-coverage/dist/lib/ascii.js new file mode 100644 index 0000000..f26caad --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/ascii.js @@ -0,0 +1,136 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const compare_1 = require("./compare"); +function emitForest(trees) { + return emitForestLines(trees).join("\n"); +} +exports.emitForest = emitForest; +function emitForestLines(trees) { + const colMap = getColMap(trees); + const header = emitOffsets(colMap); + return [header, ...trees.map(tree => emitTree(tree, colMap).join("\n"))]; +} +exports.emitForestLines = emitForestLines; +function getColMap(trees) { + const eventSet = new Set(); + for (const tree of trees) { + const stack = [tree]; + while (stack.length > 0) { + const cur = stack.pop(); + eventSet.add(cur.start); + eventSet.add(cur.end); + for (const child of cur.children) { + stack.push(child); + } + } + } + const events = [...eventSet]; + events.sort((a, b) => a - b); + let maxDigits = 1; + for (const event of events) { + maxDigits = Math.max(maxDigits, event.toString(10).length); + } + const colWidth = maxDigits + 3; + const colMap = new Map(); + for (const [i, event] of events.entries()) { + colMap.set(event, i * colWidth); + } + return colMap; +} +function emitTree(tree, colMap) { + const layers = []; + let nextLayer = [tree]; + while (nextLayer.length > 0) { + const layer = nextLayer; + layers.push(layer); + nextLayer = []; + for (const node of layer) { + for (const child of node.children) { + nextLayer.push(child); + } + } + } + return layers.map(layer => emitTreeLayer(layer, colMap)); +} +function parseFunctionRanges(text, offsetMap) { + const result = []; + for (const line of text.split("\n")) { + for (const range of parseTreeLayer(line, offsetMap)) { + result.push(range); + } + } + result.sort(compare_1.compareRangeCovs); + return result; +} +exports.parseFunctionRanges = parseFunctionRanges; +/** + * + * @param layer Sorted list of disjoint trees. + * @param colMap + */ +function emitTreeLayer(layer, colMap) { + const line = []; + let curIdx = 0; + for (const { start, end, count } of layer) { + const startIdx = colMap.get(start); + const endIdx = colMap.get(end); + if (startIdx > curIdx) { + line.push(" ".repeat(startIdx - curIdx)); + } + line.push(emitRange(count, endIdx - startIdx)); + curIdx = endIdx; + } + return line.join(""); +} +function parseTreeLayer(text, offsetMap) { + const result = []; + const regex = /\[(\d+)-*\)/gs; + while (true) { + const match = regex.exec(text); + if (match === null) { + break; + } + const startIdx = match.index; + const endIdx = startIdx + match[0].length; + const count = parseInt(match[1], 10); + const startOffset = offsetMap.get(startIdx); + const endOffset = offsetMap.get(endIdx); + if (startOffset === undefined || endOffset === undefined) { + throw new Error(`Invalid offsets for: ${JSON.stringify(text)}`); + } + result.push({ startOffset, endOffset, count }); + } + return result; +} +function emitRange(count, len) { + const rangeStart = `[${count.toString(10)}`; + const rangeEnd = ")"; + const hyphensLen = len - (rangeStart.length + rangeEnd.length); + const hyphens = "-".repeat(Math.max(0, hyphensLen)); + return `${rangeStart}${hyphens}${rangeEnd}`; +} +function emitOffsets(colMap) { + let line = ""; + for (const [event, col] of colMap) { + if (line.length < col) { + line += " ".repeat(col - line.length); + } + line += event.toString(10); + } + return line; +} +function parseOffsets(text) { + const result = new Map(); + const regex = /\d+/gs; + while (true) { + const match = regex.exec(text); + if (match === null) { + break; + } + result.set(match.index, parseInt(match[0], 10)); + } + return result; +} +exports.parseOffsets = parseOffsets; + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvYXNjaWkudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBNkM7QUFVN0MsU0FBZ0IsVUFBVSxDQUFDLEtBQXVDO0lBQ2hFLE9B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TWFwKSB7XG4gICAgaWYgKGxpbmUubGVuZ3RoIDwgY29sKSB7XG4gICAgICBsaW5lICs9IFwiIFwiLnJlcGVhdChjb2wgLSBsaW5lLmxlbmd0aCk7XG4gICAgfVxuICAgIGxpbmUgKz0gZXZlbnQudG9TdHJpbmcoMTApO1xuICB9XG4gIHJldHVybiBsaW5lO1xufVxuXG5leHBvcnQgZnVuY3Rpb24gcGFyc2VPZmZzZXRzKHRleHQ6IHN0cmluZyk6IE1hcDxudW1iZXIsIG51bWJlcj4ge1xuICBjb25zdCByZXN1bHQ6IE1hcDxudW1iZXIsIG51bWJlcj4gPSBuZXcgTWFwKCk7XG4gIGNvbnN0IHJlZ2V4OiBSZWdFeHAgPSAvXFxkKy9ncztcbiAgd2hpbGUgKHRydWUpIHtcbiAgICBjb25zdCBtYXRjaDogUmVnRXhwRXhlY0FycmF5IHwgbnVsbCA9IHJlZ2V4LmV4ZWModGV4dCk7XG4gICAgaWYgKG1hdGNoID09PSBudWxsKSB7XG4gICAgICBicmVhaztcbiAgICB9XG4gICAgcmVzdWx0LnNldChtYXRjaC5pbmRleCwgcGFyc2VJbnQobWF0Y2hbMF0sIDEwKSk7XG4gIH1cbiAgcmV0dXJuIHJlc3VsdDtcbn1cbiJdLCJzb3VyY2VSb290IjoiIn0= diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/ascii.mjs b/node_modules/@bcoe/v8-coverage/dist/lib/ascii.mjs new file mode 100644 index 0000000..050b319 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/ascii.mjs @@ -0,0 +1,130 @@ +import { compareRangeCovs } from "./compare"; +export function emitForest(trees) { + return emitForestLines(trees).join("\n"); +} +export function emitForestLines(trees) { + const colMap = getColMap(trees); + const header = emitOffsets(colMap); + return [header, ...trees.map(tree => emitTree(tree, colMap).join("\n"))]; +} +function getColMap(trees) { + const eventSet = new Set(); + for (const tree of trees) { + const stack = [tree]; + while (stack.length > 0) { + const cur = stack.pop(); + eventSet.add(cur.start); + eventSet.add(cur.end); + for (const child of cur.children) { + stack.push(child); + } + } + } + const events = [...eventSet]; + events.sort((a, b) => a - b); + let maxDigits = 1; + for (const event of events) { + maxDigits = Math.max(maxDigits, event.toString(10).length); + } + const colWidth = maxDigits + 3; + const colMap = new Map(); + for (const [i, event] of events.entries()) { + colMap.set(event, i * colWidth); + } + return colMap; +} +function emitTree(tree, colMap) { + const layers = []; + let nextLayer = [tree]; + while (nextLayer.length > 0) { + const layer = nextLayer; + layers.push(layer); + nextLayer = []; + for (const node of layer) { + for (const child of node.children) { + nextLayer.push(child); + } + } + } + return layers.map(layer => emitTreeLayer(layer, colMap)); +} +export function parseFunctionRanges(text, offsetMap) { + const result = []; + for (const line of text.split("\n")) { + for (const range of parseTreeLayer(line, offsetMap)) { + result.push(range); + } + } + result.sort(compareRangeCovs); + return result; +} +/** + * + * @param layer Sorted list of disjoint trees. + * @param colMap + */ +function emitTreeLayer(layer, colMap) { + const line = []; + let curIdx = 0; + for (const { start, end, count } of layer) { + const startIdx = colMap.get(start); + const endIdx = colMap.get(end); + if (startIdx > curIdx) { + line.push(" ".repeat(startIdx - curIdx)); + } + line.push(emitRange(count, endIdx - startIdx)); + curIdx = endIdx; + } + return line.join(""); +} +function parseTreeLayer(text, offsetMap) { + const result = []; + const regex = /\[(\d+)-*\)/gs; + while (true) { + const match = regex.exec(text); + if (match === null) { + break; + } + const startIdx = match.index; + const endIdx = startIdx + match[0].length; + const count = parseInt(match[1], 10); + const startOffset = offsetMap.get(startIdx); + const endOffset = offsetMap.get(endIdx); + if (startOffset === undefined || endOffset === undefined) { + throw new Error(`Invalid offsets for: ${JSON.stringify(text)}`); + } + result.push({ startOffset, endOffset, count }); + } + return result; +} +function emitRange(count, len) { + const rangeStart = `[${count.toString(10)}`; + const rangeEnd = ")"; + const hyphensLen = len - (rangeStart.length + rangeEnd.length); + const hyphens = "-".repeat(Math.max(0, hyphensLen)); + return `${rangeStart}${hyphens}${rangeEnd}`; +} +function emitOffsets(colMap) { + let line = ""; + for (const [event, col] of colMap) { + if (line.length < col) { + line += " ".repeat(col - line.length); + } + line += event.toString(10); + } + return line; +} +export function parseOffsets(text) { + const result = new Map(); + const regex = /\d+/gs; + while (true) { + const match = regex.exec(text); + if (match === null) { + break; + } + result.set(match.index, parseInt(match[0], 10)); + } + return result; +} + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvYXNjaWkudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUFFLGdCQUFnQixFQUFFLE1BQU0sV0FBVyxDQUFDO0FBVTdDLE1BQU0sVUFBVSxVQUFVLENBQUMsS0FBdUM7SUFDaEUsT0FBTyxlQUFlLENBQUMsS0FBSyxDQUFDLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQzNDLENBQUM7QUFFRCxNQUFNLFVBQVUsZUFBZSxDQUFDLEtBQXVDO0lBQ3JFLE1BQU0sTUFBTSxHQUF3QixTQUFTLENBQUMsS0FBSyxDQUFDLENBQUM7SUFDckQsTUFBTSxNQUFNLEdBQVcsV0FBVyxDQUFDLE1BQU0sQ0FBQyxDQUFDO0lBQzNDLE9BQU8sQ0FBQyxNQUFNLEVBQUUsR0FBRyxLQUFLLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBQyxFQUFFLENBQUMsUUFBUSxDQUFDLElBQUksRUFBRSxNQUFNLENBQUMsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDO0FBQzNFLENBQUM7QUFFRCxTQUFTLFNBQVMsQ0FBQyxLQUFrQztJQUNuRCxNQUFNLFFBQVEsR0FBZ0IsSUFBSSxHQUFHLEVBQUUsQ0FBQztJQUN4QyxLQUFLLE1BQU0sSUFBSSxJQUFJLEtBQUssRUFBRTtRQUN4QixNQUFNLEtBQUssR0FBd0IsQ0FBQyxJQUFJLENBQUMsQ0FBQztRQUMxQ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.ts b/node_modules/@bcoe/v8-coverage/dist/lib/clone.d.ts new file mode 100644 index 0000000..a082032 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/clone.d.ts @@ -0,0 +1,29 @@ +import { FunctionCov, ProcessCov, RangeCov, ScriptCov } from "./types"; +/** + * Creates a deep copy of a process coverage. + * + * @param processCov Process coverage to clone. + * @return Cloned process coverage. + */ +export declare function cloneProcessCov(processCov: Readonly): ProcessCov; +/** + * Creates a deep copy of a script coverage. + * + * @param scriptCov Script coverage to clone. + * @return Cloned script coverage. + */ +export declare function cloneScriptCov(scriptCov: Readonly): ScriptCov; +/** + * Creates a deep copy of a function coverage. + * + * @param functionCov Function coverage to clone. + * @return Cloned function coverage. + */ +export declare function cloneFunctionCov(functionCov: Readonly): FunctionCov; +/** + * Creates a deep copy of a function coverage. + * + * @param rangeCov Range coverage to clone. + * @return Cloned range coverage. + */ +export declare function cloneRangeCov(rangeCov: Readonly): RangeCov; diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/clone.js b/node_modules/@bcoe/v8-coverage/dist/lib/clone.js new file mode 100644 index 0000000..4e8a823 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/clone.js @@ -0,0 +1,70 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Creates a deep copy of a process coverage. + * + * @param processCov Process coverage to clone. + * @return Cloned process coverage. + */ +function cloneProcessCov(processCov) { + const result = []; + for (const scriptCov of processCov.result) { + result.push(cloneScriptCov(scriptCov)); + } + return { + result, + }; +} +exports.cloneProcessCov = cloneProcessCov; +/** + * Creates a deep copy of a script coverage. + * + * @param scriptCov Script coverage to clone. + * @return Cloned script coverage. + */ +function cloneScriptCov(scriptCov) { + const functions = []; + for (const functionCov of scriptCov.functions) { + functions.push(cloneFunctionCov(functionCov)); + } + return { + scriptId: scriptCov.scriptId, + url: scriptCov.url, + functions, + }; +} +exports.cloneScriptCov = cloneScriptCov; +/** + * Creates a deep copy of a function coverage. + * + * @param functionCov Function coverage to clone. + * @return Cloned function coverage. + */ +function cloneFunctionCov(functionCov) { + const ranges = []; + for (const rangeCov of functionCov.ranges) { + ranges.push(cloneRangeCov(rangeCov)); + } + return { + functionName: functionCov.functionName, + ranges, + isBlockCoverage: functionCov.isBlockCoverage, + }; +} +exports.cloneFunctionCov = cloneFunctionCov; +/** + * Creates a deep copy of a function coverage. + * + * @param rangeCov Range coverage to clone. + * @return Cloned range coverage. + */ +function cloneRangeCov(rangeCov) { + return { + startOffset: rangeCov.startOffset, + endOffset: rangeCov.endOffset, + count: rangeCov.count, + }; +} +exports.cloneRangeCov = cloneRangeCov; + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvY2xvbmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFFQTs7Ozs7R0FLRztBQUNILFNBQWdCLGVBQWUsQ0FBQyxVQUFnQztJQUM5RCxNQUFNLE1BQU0sR0FBZ0IsRUFBRSxDQUFDO0lBQy9CLEtBQUssTUFBTSxTQUFTLElBQUksVUFBVSxDQUFDLE1BQU0sRUFBRTtRQUN6QyxNQUFNLENBQUMsSUFBSSxDQUFDLGNBQWMsQ0FBQyxTQUFTLENBQUMsQ0FBQyxDQUFDO0tBQ3hDO0lBRUQsT0FBTztRQUNMLE1BQU07S0FDUCxDQUFDO0FBQ0osQ0FBQztBQVRELDBDQVNDO0FBRUQ7Ozs7O0dBS0c7QUFDSCxTQUFnQixjQUFjLENBQUMsU0FBOEI7SUFDM0QsTUFBTSxTQUFTLEdBQWtCLEVBQUUsQ0FBQztJQUNwQyxLQUFLLE1BQU0sV0FBVyxJQUFJLFNBQVMsQ0FBQyxTQUFTLEVBQUU7UUFDN0MsU0FBUyxDQUFDLElBQUksQ0FBQyxnQkFBZ0IsQ0FBQyxXQUFXLENBQUMsQ0FBQyxDQUFDO0tBQy9DO0lBRUQsT0FBTztRQUNMLFFBQVEsRUFB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LmNvdW50LFxuICB9O1xufVxuIl0sInNvdXJjZVJvb3QiOiIifQ== diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/clone.mjs b/node_modules/@bcoe/v8-coverage/dist/lib/clone.mjs new file mode 100644 index 0000000..87482d6 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/clone.mjs @@ -0,0 +1,64 @@ +/** + * Creates a deep copy of a process coverage. + * + * @param processCov Process coverage to clone. + * @return Cloned process coverage. + */ +export function cloneProcessCov(processCov) { + const result = []; + for (const scriptCov of processCov.result) { + result.push(cloneScriptCov(scriptCov)); + } + return { + result, + }; +} +/** + * Creates a deep copy of a script coverage. + * + * @param scriptCov Script coverage to clone. + * @return Cloned script coverage. + */ +export function cloneScriptCov(scriptCov) { + const functions = []; + for (const functionCov of scriptCov.functions) { + functions.push(cloneFunctionCov(functionCov)); + } + return { + scriptId: scriptCov.scriptId, + url: scriptCov.url, + functions, + }; +} +/** + * Creates a deep copy of a function coverage. + * + * @param functionCov Function coverage to clone. + * @return Cloned function coverage. + */ +export function cloneFunctionCov(functionCov) { + const ranges = []; + for (const rangeCov of functionCov.ranges) { + ranges.push(cloneRangeCov(rangeCov)); + } + return { + functionName: functionCov.functionName, + ranges, + isBlockCoverage: functionCov.isBlockCoverage, + }; +} +/** + * Creates a deep copy of a function coverage. + * + * @param rangeCov Range coverage to clone. + * @return Cloned range coverage. + */ +export function cloneRangeCov(rangeCov) { + return { + startOffset: rangeCov.startOffset, + endOffset: rangeCov.endOffset, + count: rangeCov.count, + }; +} + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvY2xvbmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBRUE7Ozs7O0dBS0c7QUFDSCxNQUFNLFVBQVUsZUFBZSxDQUFDLFVBQWdDO0lBQzlELE1BQU0sTUFBTSxHQUFnQixFQUFFLENBQUM7SUFDL0IsS0FBSyxNQUFN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uXG4vKipcbiAqIENyZWF0ZXMgYSBkZWVwIGNvcHkgb2YgYSBmdW5jdGlvbiBjb3ZlcmFnZS5cbiAqXG4gKiBAcGFyYW0gcmFuZ2VDb3YgUmFuZ2UgY292ZXJhZ2UgdG8gY2xvbmUuXG4gKiBAcmV0dXJuIENsb25lZCByYW5nZSBjb3ZlcmFnZS5cbiAqL1xuZXhwb3J0IGZ1bmN0aW9uIGNsb25lUmFuZ2VDb3YocmFuZ2VDb3Y6IFJlYWRvbmx5PFJhbmdlQ292Pik6IFJhbmdlQ292IHtcbiAgcmV0dXJuIHtcbiAgICBzdGFydE9mZnNldDogcmFuZ2VDb3Yuc3RhcnRPZmZzZXQsXG4gICAgZW5kT2Zmc2V0OiByYW5nZUNvdi5lbmRPZmZzZXQsXG4gICAgY291bnQ6IHJhbmdlQ292LmNvdW50LFxuICB9O1xufVxuIl0sInNvdXJjZVJvb3QiOiIifQ== diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/compare.d.ts b/node_modules/@bcoe/v8-coverage/dist/lib/compare.d.ts new file mode 100644 index 0000000..5fee68b --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/compare.d.ts @@ -0,0 +1,21 @@ +import { FunctionCov, RangeCov, ScriptCov } from "./types"; +/** + * Compares two script coverages. + * + * The result corresponds to the comparison of their `url` value (alphabetical sort). + */ +export declare function compareScriptCovs(a: Readonly, b: Readonly): number; +/** + * Compares two function coverages. + * + * The result corresponds to the comparison of the root ranges. + */ +export declare function compareFunctionCovs(a: Readonly, b: Readonly): number; +/** + * Compares two range coverages. + * + * The ranges are first ordered by ascending `startOffset` and then by + * descending `endOffset`. + * This corresponds to a pre-order tree traversal. + */ +export declare function compareRangeCovs(a: Readonly, b: Readonly): number; diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/compare.js b/node_modules/@bcoe/v8-coverage/dist/lib/compare.js new file mode 100644 index 0000000..c723ea0 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/compare.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Compares two script coverages. + * + * The result corresponds to the comparison of their `url` value (alphabetical sort). + */ +function compareScriptCovs(a, b) { + if (a.url === b.url) { + return 0; + } + else if (a.url < b.url) { + return -1; + } + else { + return 1; + } +} +exports.compareScriptCovs = compareScriptCovs; +/** + * Compares two function coverages. + * + * The result corresponds to the comparison of the root ranges. + */ +function compareFunctionCovs(a, b) { + return compareRangeCovs(a.ranges[0], b.ranges[0]); +} +exports.compareFunctionCovs = compareFunctionCovs; +/** + * Compares two range coverages. + * + * The ranges are first ordered by ascending `startOffset` and then by + * descending `endOffset`. + * This corresponds to a pre-order tree traversal. + */ +function compareRangeCovs(a, b) { + if (a.startOffset !== b.startOffset) { + return a.startOffset - b.startOffset; + } + else { + return b.endOffset - a.endOffset; + } +} +exports.compareRangeCovs = compareRangeCovs; + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvY29tcGFyZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOzs7O0dBSUc7QUFDSCxTQUFnQixpQkFBaUIsQ0FBQyxDQUFzQixFQUFFLENBQXNCO0lBQzlFLElBQUksQ0FBQyxDQUFDLEdBQUcsS0FBSyxDQUFDLENBQUMsR0FBRyxFQUFFO1FBQ25CLE9BQU8sQ0FBQyxDQUFDO0tBQ1Y7U0FBTSxJQUFJLENBQUMsQ0FBQyxHQUFHLEdBQUcsQ0FBQyxDQUFDLEdBQUcsRUFBRTtRQUN4QixPQUFPLENBQUMsQ0FBQyxDQUFDO0tBQ1g7U0FBTTtRQUNMLE9BQU8sQ0FBQyxDQUFDO0tBQ1Y7QUFDSCxDQUFDO0FBUkQsOENBUUM7QUFFRDs7OztHQUlHO0FBQ0gsU0FBZ0IsbUJBQW1CLENBQUMsQ0FBd0IsRUFBRSxDQUF3QjtJQUNwRixPQUFPLGdCQU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mjs new file mode 100644 index 0000000..c03be82 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/compare.mjs @@ -0,0 +1,41 @@ +/** + * Compares two script coverages. + * + * The result corresponds to the comparison of their `url` value (alphabetical sort). + */ +export function compareScriptCovs(a, b) { + if (a.url === b.url) { + return 0; + } + else if (a.url < b.url) { + return -1; + } + else { + return 1; + } +} +/** + * Compares two function coverages. + * + * The result corresponds to the comparison of the root ranges. + */ +export function compareFunctionCovs(a, b) { + return compareRangeCovs(a.ranges[0], b.ranges[0]); +} +/** + * Compares two range coverages. + * + * The ranges are first ordered by ascending `startOffset` and then by + * descending `endOffset`. + * This corresponds to a pre-order tree traversal. + */ +export function compareRangeCovs(a, b) { + if (a.startOffset !== b.startOffset) { + return a.startOffset - b.startOffset; + } + else { + return b.endOffset - a.endOffset; + } +} + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvY29tcGFyZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFFQTs7OztHQUlHO0FBQ0gsTUFBTSxVQUFVLGlCQUFpQixDQUFDLENBQXNCLEVBQUUsQ0FBc0I7SUFDOUUsSUFBSSxDQUFDLENBQUMsR0FBRyxLQUFLLENBQUMsQ0FBQyxHQUFHLEVBQUU7UUFDbkIsT0FBTyxDQUFDLENBQUM7S0FDVjtTQUFNLElBQUksQ0FBQyxDQUFDLEdBQUcsR0FBRyxDQUFDLENBQUMsR0FBRyxFQUFFO1FBQ3hCLE9BQU8sQ0FBQyxDQUFDLENBQUM7S0FDWDtTQUFNO1FBQ0wsT0FBTyxDQUFDLENBQUM7S0FDVjtBQUNILENBQUM7QUFFRDs7OztHQUlHO0FBQ0gsTUFBTSxVQUFVLG1CQUFtQixDQUFDLENBQXdCLEVBQUUsQ0FBd0I7SUFDcEYsT0FBTyxnQkFBZ0IsQ0FBQyxDQUFDLENBQUMsTUFBTSxDQUFDLENBQUMsQ0F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XMuXG4gKlxuICogVGhlIHJlc3VsdCBjb3JyZXNwb25kcyB0byB0aGUgY29tcGFyaXNvbiBvZiB0aGUgcm9vdCByYW5nZXMuXG4gKi9cbmV4cG9ydCBmdW5jdGlvbiBjb21wYXJlRnVuY3Rpb25Db3ZzKGE6IFJlYWRvbmx5PEZ1bmN0aW9uQ292PiwgYjogUmVhZG9ubHk8RnVuY3Rpb25Db3Y+KTogbnVtYmVyIHtcbiAgcmV0dXJuIGNvbXBhcmVSYW5nZUNvdnMoYS5yYW5nZXNbMF0sIGIucmFuZ2VzWzBdKTtcbn1cblxuLyoqXG4gKiBDb21wYXJlcyB0d28gcmFuZ2UgY292ZXJhZ2VzLlxuICpcbiAqIFRoZSByYW5nZXMgYXJlIGZpcnN0IG9yZGVyZWQgYnkgYXNjZW5kaW5nIGBzdGFydE9mZnNldGAgYW5kIHRoZW4gYnlcbiAqIGRlc2NlbmRpbmcgYGVuZE9mZnNldGAuXG4gKiBUaGlzIGNvcnJlc3BvbmRzIHRvIGEgcHJlLW9yZGVyIHRyZWUgdHJhdmVyc2FsLlxuICovXG5leHBvcnQgZnVuY3Rpb24gY29tcGFyZVJhbmdlQ292cyhhOiBSZWFkb25seTxSYW5nZUNvdj4sIGI6IFJlYWRvbmx5PFJhbmdlQ292Pik6IG51bWJlciB7XG4gIGlmIChhLnN0YXJ0T2Zmc2V0ICE9PSBiLnN0YXJ0T2Zmc2V0KSB7XG4gICAgcmV0dXJuIGEuc3RhcnRPZmZzZXQgLSBiLnN0YXJ0T2Zmc2V0O1xuICB9IGVsc2Uge1xuICAgIHJldHVybiBiLmVuZE9mZnNldCAtIGEuZW5kT2Zmc2V0O1xuICB9XG59XG4iXSwic291cmNlUm9vdCI6IiJ9 diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/index.d.ts b/node_modules/@bcoe/v8-coverage/dist/lib/index.d.ts new file mode 100644 index 0000000..f92bdf3 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/index.d.ts @@ -0,0 +1,6 @@ +export { emitForest, emitForestLines, parseFunctionRanges, parseOffsets } from "./ascii"; +export { cloneFunctionCov, cloneProcessCov, cloneScriptCov, cloneRangeCov } from "./clone"; +export { compareScriptCovs, compareFunctionCovs, compareRangeCovs } from "./compare"; +export { mergeFunctionCovs, mergeProcessCovs, mergeScriptCovs } from "./merge"; +export { RangeTree } from "./range-tree"; +export { ProcessCov, ScriptCov, FunctionCov, RangeCov } from "./types"; diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/index.js b/node_modules/@bcoe/v8-coverage/dist/lib/index.js new file mode 100644 index 0000000..450362d --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/index.js @@ -0,0 +1,24 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var ascii_1 = require("./ascii"); +exports.emitForest = ascii_1.emitForest; +exports.emitForestLines = ascii_1.emitForestLines; +exports.parseFunctionRanges = ascii_1.parseFunctionRanges; +exports.parseOffsets = ascii_1.parseOffsets; +var clone_1 = require("./clone"); +exports.cloneFunctionCov = clone_1.cloneFunctionCov; +exports.cloneProcessCov = clone_1.cloneProcessCov; +exports.cloneScriptCov = clone_1.cloneScriptCov; +exports.cloneRangeCov = clone_1.cloneRangeCov; +var compare_1 = require("./compare"); +exports.compareScriptCovs = compare_1.compareScriptCovs; +exports.compareFunctionCovs = compare_1.compareFunctionCovs; +exports.compareRangeCovs = compare_1.compareRangeCovs; +var merge_1 = require("./merge"); +exports.mergeFunctionCovs = merge_1.mergeFunctionCovs; +exports.mergeProcessCovs = merge_1.mergeProcessCovs; +exports.mergeScriptCovs = merge_1.mergeScriptCovs; +var range_tree_1 = require("./range-tree"); +exports.RangeTree = range_tree_1.RangeTree; + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpQ0FBeUY7QUFBaE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bmV4cG9ydCB7IFJhbmdlVHJlZSB9IGZyb20gXCIuL3JhbmdlLXRyZWVcIjtcbmV4cG9ydCB7IFByb2Nlc3NDb3YsIFNjcmlwdENvdiwgRnVuY3Rpb25Db3YsIFJhbmdlQ292IH0gZnJvbSBcIi4vdHlwZXNcIjtcbiJdLCJzb3VyY2VSb290IjoiIn0= diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/index.mjs b/node_modules/@bcoe/v8-coverage/dist/lib/index.mjs new file mode 100644 index 0000000..30d8ce1 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/index.mjs @@ -0,0 +1,7 @@ +export { emitForest, emitForestLines, parseFunctionRanges, parseOffsets } from "./ascii"; +export { cloneFunctionCov, cloneProcessCov, cloneScriptCov, cloneRangeCov } from "./clone"; +export { compareScriptCovs, compareFunctionCovs, compareRangeCovs } from "./compare"; +export { mergeFunctionCovs, mergeProcessCovs, mergeScriptCovs } from "./merge"; +export { RangeTree } from "./range-tree"; + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUFFLFVBQVUsRUFBRSxlQUFlLEVBQUUsbUJBQW1CLEVBQUUsWUFBWSxFQUFFLE1BQU0sU0FBUyxDQUFDO0FBQ3pGLE9BQU8sRUFBRSxnQkFBZ0IsRUFBRSxlQUFlLEVBQUUsY0FBYyxFQUFFLGFBQWEsRUFBRSxNQUFNLFNBQVMsQ0FBQztBQUMzRixPQUFPLEVBQUUsaUJBQWlCLEVBQUUsbUJBQW1CLEVBQUUsZ0JBQWdCLEVBQUUsTUFBTSxXQUFXLENBQUM7QUFDckYsT0FBTyxFQUFFLGlCQUFpQixFQUFFLGdCQUFnQixFQUFFLGVBQWUsRUFBRSxNQUFNLFNBQVMsQ0FBQztBQUMvRSxPQUFPLEVBQUUsU0FBUyxFQUFFLE1BQU0sY0FBYyxDQUFDIiwiZmlsZSI6ImluZGV4LmpzIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IHsgZW1pdEZvcmVzdCwgZW1pdEZvcmVzdExpbmVzLCBwYXJzZUZ1bmN0aW9uUmFuZ2VzLCBwYXJzZU9mZnNldHMgfSBmcm9tIFwiLi9hc2NpaVwiO1xuZXhwb3J0IHsgY2xvbmVGdW5jdGlvbkNvdiwgY2xvbmVQcm9jZXNzQ292LCBjbG9uZVNjcmlwdENvdiwgY2xvbmVSYW5nZUNvdiB9IGZyb20gXCIuL2Nsb25lXCI7XG5leHBvcnQgeyBjb21wYXJlU2NyaXB0Q292cywgY29tcGFyZUZ1bmN0aW9uQ292cywgY29tcGFyZVJhbmdlQ292cyB9IGZyb20gXCIuL2NvbXBhcmVcIjtcbmV4cG9ydCB7IG1lcmdlRnVuY3Rpb25Db3ZzLCBtZXJnZVByb2Nlc3NDb3ZzLCBtZXJnZVNjcmlwdENvdnMgfSBmcm9tIFwiLi9tZXJnZVwiO1xuZXhwb3J0IHsgUmFuZ2VUcmVlIH0gZnJvbSBcIi4vcmFuZ2UtdHJlZVwiO1xuZXhwb3J0IHsgUHJvY2Vzc0NvdiwgU2NyaXB0Q292LCBGdW5jdGlvbkNvdiwgUmFuZ2VDb3YgfSBmcm9tIFwiLi90eXBlc1wiO1xuIl0sInNvdXJjZVJvb3QiOiIifQ== diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/merge.d.ts b/node_modules/@bcoe/v8-coverage/dist/lib/merge.d.ts new file mode 100644 index 0000000..5095383 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/merge.d.ts @@ -0,0 +1,39 @@ +import { FunctionCov, ProcessCov, ScriptCov } from "./types"; +/** + * Merges a list of process coverages. + * + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param processCovs Process coverages to merge. + * @return Merged process coverage. + */ +export declare function mergeProcessCovs(processCovs: ReadonlyArray): ProcessCov; +/** + * Merges a list of matching script coverages. + * + * Scripts are matching if they have the same `url`. + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param scriptCovs Process coverages to merge. + * @return Merged script coverage, or `undefined` if the input list was empty. + */ +export declare function mergeScriptCovs(scriptCovs: ReadonlyArray): ScriptCov | undefined; +/** + * Merges a list of matching function coverages. + * + * Functions are matching if their root ranges have the same span. + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param funcCovs Function coverages to merge. + * @return Merged function coverage, or `undefined` if the input list was empty. + */ +export declare function mergeFunctionCovs(funcCovs: ReadonlyArray): FunctionCov | undefined; diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/merge.js b/node_modules/@bcoe/v8-coverage/dist/lib/merge.js new file mode 100644 index 0000000..c2b5a8c --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/merge.js @@ -0,0 +1,302 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const normalize_1 = require("./normalize"); +const range_tree_1 = require("./range-tree"); +/** + * Merges a list of process coverages. + * + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param processCovs Process coverages to merge. + * @return Merged process coverage. + */ +function mergeProcessCovs(processCovs) { + if (processCovs.length === 0) { + return { result: [] }; + } + const urlToScripts = new Map(); + for (const processCov of processCovs) { + for (const scriptCov of processCov.result) { + let scriptCovs = urlToScripts.get(scriptCov.url); + if (scriptCovs === undefined) { + scriptCovs = []; + urlToScripts.set(scriptCov.url, scriptCovs); + } + scriptCovs.push(scriptCov); + } + } + const result = []; + for (const scripts of urlToScripts.values()) { + // assert: `scripts.length > 0` + result.push(mergeScriptCovs(scripts)); + } + const merged = { result }; + normalize_1.normalizeProcessCov(merged); + return merged; +} +exports.mergeProcessCovs = mergeProcessCovs; +/** + * Merges a list of matching script coverages. + * + * Scripts are matching if they have the same `url`. + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param scriptCovs Process coverages to merge. + * @return Merged script coverage, or `undefined` if the input list was empty. + */ +function mergeScriptCovs(scriptCovs) { + if (scriptCovs.length === 0) { + return undefined; + } + else if (scriptCovs.length === 1) { + const merged = scriptCovs[0]; + normalize_1.deepNormalizeScriptCov(merged); + return merged; + } + const first = scriptCovs[0]; + const scriptId = first.scriptId; + const url = first.url; + const rangeToFuncs = new Map(); + for (const scriptCov of scriptCovs) { + for (const funcCov of scriptCov.functions) { + const rootRange = stringifyFunctionRootRange(funcCov); + let funcCovs = rangeToFuncs.get(rootRange); + if (funcCovs === undefined || + // if the entry in rangeToFuncs is function-level granularity and + // the new coverage is block-level, prefer block-level. + (!funcCovs[0].isBlockCoverage && funcCov.isBlockCoverage)) { + funcCovs = []; + rangeToFuncs.set(rootRange, funcCovs); + } + else if (funcCovs[0].isBlockCoverage && !funcCov.isBlockCoverage) { + // if the entry in rangeToFuncs is block-level granularity, we should + // not append function level granularity. + continue; + } + funcCovs.push(funcCov); + } + } + const functions = []; + for (const funcCovs of rangeToFuncs.values()) { + // assert: `funcCovs.length > 0` + functions.push(mergeFunctionCovs(funcCovs)); + } + const merged = { scriptId, url, functions }; + normalize_1.normalizeScriptCov(merged); + return merged; +} +exports.mergeScriptCovs = mergeScriptCovs; +/** + * Returns a string representation of the root range of the function. + * + * This string can be used to match function with same root range. + * The string is derived from the start and end offsets of the root range of + * the function. + * This assumes that `ranges` is non-empty (true for valid function coverages). + * + * @param funcCov Function coverage with the range to stringify + * @internal + */ +function stringifyFunctionRootRange(funcCov) { + const rootRange = funcCov.ranges[0]; + return `${rootRange.startOffset.toString(10)};${rootRange.endOffset.toString(10)}`; +} +/** + * Merges a list of matching function coverages. + * + * Functions are matching if their root ranges have the same span. + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param funcCovs Function coverages to merge. + * @return Merged function coverage, or `undefined` if the input list was empty. + */ +function mergeFunctionCovs(funcCovs) { + if (funcCovs.length === 0) { + return undefined; + } + else if (funcCovs.length === 1) { + const merged = funcCovs[0]; + normalize_1.normalizeFunctionCov(merged); + return merged; + } + const functionName = funcCovs[0].functionName; + const trees = []; + for (const funcCov of funcCovs) { + // assert: `fn.ranges.length > 0` + // assert: `fn.ranges` is sorted + trees.push(range_tree_1.RangeTree.fromSortedRanges(funcCov.ranges)); + } + // assert: `trees.length > 0` + const mergedTree = mergeRangeTrees(trees); + normalize_1.normalizeRangeTree(mergedTree); + const ranges = mergedTree.toRanges(); + const isBlockCoverage = !(ranges.length === 1 && ranges[0].count === 0); + const merged = { functionName, ranges, isBlockCoverage }; + // assert: `merged` is normalized + return merged; +} +exports.mergeFunctionCovs = mergeFunctionCovs; +/** + * @precondition Same `start` and `end` for all the trees + */ +function mergeRangeTrees(trees) { + if (trees.length <= 1) { + return trees[0]; + } + const first = trees[0]; + let delta = 0; + for (const tree of trees) { + delta += tree.delta; + } + const children = mergeRangeTreeChildren(trees); + return new range_tree_1.RangeTree(first.start, first.end, delta, children); +} +class RangeTreeWithParent { + constructor(parentIndex, tree) { + this.parentIndex = parentIndex; + this.tree = tree; + } +} +class StartEvent { + constructor(offset, trees) { + this.offset = offset; + this.trees = trees; + } + static compare(a, b) { + return a.offset - b.offset; + } +} +class StartEventQueue { + constructor(queue) { + this.queue = queue; + this.nextIndex = 0; + this.pendingOffset = 0; + this.pendingTrees = undefined; + } + static fromParentTrees(parentTrees) { + const startToTrees = new Map(); + for (const [parentIndex, parentTree] of parentTrees.entries()) { + for (const child of parentTree.children) { + let trees = startToTrees.get(child.start); + if (trees === undefined) { + trees = []; + startToTrees.set(child.start, trees); + } + trees.push(new RangeTreeWithParent(parentIndex, child)); + } + } + const queue = []; + for (const [startOffset, trees] of startToTrees) { + queue.push(new StartEvent(startOffset, trees)); + } + queue.sort(StartEvent.compare); + return new StartEventQueue(queue); + } + setPendingOffset(offset) { + this.pendingOffset = offset; + } + pushPendingTree(tree) { + if (this.pendingTrees === undefined) { + this.pendingTrees = []; + } + this.pendingTrees.push(tree); + } + next() { + const pendingTrees = this.pendingTrees; + const nextEvent = this.queue[this.nextIndex]; + if (pendingTrees === undefined) { + this.nextIndex++; + return nextEvent; + } + else if (nextEvent === undefined) { + this.pendingTrees = undefined; + return new StartEvent(this.pendingOffset, pendingTrees); + } + else { + if (this.pendingOffset < nextEvent.offset) { + this.pendingTrees = undefined; + return new StartEvent(this.pendingOffset, pendingTrees); + } + else { + if (this.pendingOffset === nextEvent.offset) { + this.pendingTrees = undefined; + for (const tree of pendingTrees) { + nextEvent.trees.push(tree); + } + } + this.nextIndex++; + return nextEvent; + } + } + } +} +function mergeRangeTreeChildren(parentTrees) { + const result = []; + const startEventQueue = StartEventQueue.fromParentTrees(parentTrees); + const parentToNested = new Map(); + let openRange; + while (true) { + const event = startEventQueue.next(); + if (event === undefined) { + break; + } + if (openRange !== undefined && openRange.end <= event.offset) { + result.push(nextChild(openRange, parentToNested)); + openRange = undefined; + } + if (openRange === undefined) { + let openRangeEnd = event.offset + 1; + for (const { parentIndex, tree } of event.trees) { + openRangeEnd = Math.max(openRangeEnd, tree.end); + insertChild(parentToNested, parentIndex, tree); + } + startEventQueue.setPendingOffset(openRangeEnd); + openRange = { start: event.offset, end: openRangeEnd }; + } + else { + for (const { parentIndex, tree } of event.trees) { + if (tree.end > openRange.end) { + const right = tree.split(openRange.end); + startEventQueue.pushPendingTree(new RangeTreeWithParent(parentIndex, right)); + } + insertChild(parentToNested, parentIndex, tree); + } + } + } + if (openRange !== undefined) { + result.push(nextChild(openRange, parentToNested)); + } + return result; +} +function insertChild(parentToNested, parentIndex, tree) { + let nested = parentToNested.get(parentIndex); + if (nested === undefined) { + nested = []; + parentToNested.set(parentIndex, nested); + } + nested.push(tree); +} +function nextChild(openRange, parentToNested) { + const matchingTrees = []; + for (const nested of parentToNested.values()) { + if (nested.length === 1 && nested[0].start === openRange.start && nested[0].end === openRange.end) { + matchingTrees.push(nested[0]); + } + else { + matchingTrees.push(new range_tree_1.RangeTree(openRange.start, openRange.end, 0, nested)); + } + } + parentToNested.clear(); + return mergeRangeTrees(matchingTrees); +} + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvbWVyZ2UudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSwyQ0FNcUI7QUFDckIsNkNBQXlDO0FBR3pDOzs7Ozs7Ozs7O0dBVUc7QUFDSCxTQUFnQixnQkFBZ0IsQ0FBQyxXQUFzQztJQUNyRSxJQUFJLFdBQVcsQ0FBQyxNQUFNLEtBQUssQ0FBQyxFQUFFO1FBQzVCLE9BQU8sRUFBQyxNQUFNLEVBQUUsRUFBRSxFQUFDLENBQUM7S0FDckI7SUFFRCxNQUFNLFlBQVksR0FBNkIsSUFBSSxHQUFHLEVBQUUsQ0FBQztJQUN6RCxLQUFLLE1BQU0sVUFBVSxJQUFJLFdBQVcsRUFBRTtRQUNwQyxLQUFLLE1BQU0sU0FBUyxJQUFJLFVBQVUsQ0FBQyxNQUFNLEVBQUU7WUFDekMsSUFBSSxVQUFVLEdBQTRCLFlBQVksQ0FBQyxHQUFHLENBQUMsU0FBUyxDQUFDLEdBQUcsQ0FBQyxDQUFDO1lBQzFFLElBQUksVUFBVSxLQUFLLFNBQVMsRUFBRTtnQkFDNUIsVUFBVSxHQUFHLEVBQUUsQ0FBQztnQkFDaEIsWUFBWSxDQUFDLEdBQUcsQ0FBQyxTQUFTLENBQUMsR0FBRyxFQUFFLFVBQVUsQ0FBQyxDQUFDO2FBQzdDO1lBQ0QsVUFBVSxDQUFDLElBQUksQ0FBQyxTQUFTLENBQUMsQ0FBQztTQUM1QjtLQUNGO0lBRUQsTUFBTSxNQUFNLEdBQWdCLEVBQUUsQ0FBQztJQUMvQixLQUFLLE1BQU0sT0FBTyxJQUFJLFlBQVksQ0FBQyxNQUFNLEVB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0ZWQgb2YgcGFyZW50VG9OZXN0ZWQudmFsdWVzKCkpIHtcbiAgICBpZiAobmVzdGVkLmxlbmd0aCA9PT0gMSAmJiBuZXN0ZWRbMF0uc3RhcnQgPT09IG9wZW5SYW5nZS5zdGFydCAmJiBuZXN0ZWRbMF0uZW5kID09PSBvcGVuUmFuZ2UuZW5kKSB7XG4gICAgICBtYXRjaGluZ1RyZWVzLnB1c2gobmVzdGVkWzBdKTtcbiAgICB9IGVsc2Uge1xuICAgICAgbWF0Y2hpbmdUcmVlcy5wdXNoKG5ldyBSYW5nZVRyZWUoXG4gICAgICAgIG9wZW5SYW5nZS5zdGFydCxcbiAgICAgICAgb3BlblJhbmdlLmVuZCxcbiAgICAgICAgMCxcbiAgICAgICAgbmVzdGVkLFxuICAgICAgKSk7XG4gICAgfVxuICB9XG4gIHBhcmVudFRvTmVzdGVkLmNsZWFyKCk7XG4gIHJldHVybiBtZXJnZVJhbmdlVHJlZXMobWF0Y2hpbmdUcmVlcykhO1xufVxuIl0sInNvdXJjZVJvb3QiOiIifQ== diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/merge.mjs b/node_modules/@bcoe/v8-coverage/dist/lib/merge.mjs new file mode 100644 index 0000000..242fce9 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/merge.mjs @@ -0,0 +1,297 @@ +import { deepNormalizeScriptCov, normalizeFunctionCov, normalizeProcessCov, normalizeRangeTree, normalizeScriptCov, } from "./normalize"; +import { RangeTree } from "./range-tree"; +/** + * Merges a list of process coverages. + * + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param processCovs Process coverages to merge. + * @return Merged process coverage. + */ +export function mergeProcessCovs(processCovs) { + if (processCovs.length === 0) { + return { result: [] }; + } + const urlToScripts = new Map(); + for (const processCov of processCovs) { + for (const scriptCov of processCov.result) { + let scriptCovs = urlToScripts.get(scriptCov.url); + if (scriptCovs === undefined) { + scriptCovs = []; + urlToScripts.set(scriptCov.url, scriptCovs); + } + scriptCovs.push(scriptCov); + } + } + const result = []; + for (const scripts of urlToScripts.values()) { + // assert: `scripts.length > 0` + result.push(mergeScriptCovs(scripts)); + } + const merged = { result }; + normalizeProcessCov(merged); + return merged; +} +/** + * Merges a list of matching script coverages. + * + * Scripts are matching if they have the same `url`. + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param scriptCovs Process coverages to merge. + * @return Merged script coverage, or `undefined` if the input list was empty. + */ +export function mergeScriptCovs(scriptCovs) { + if (scriptCovs.length === 0) { + return undefined; + } + else if (scriptCovs.length === 1) { + const merged = scriptCovs[0]; + deepNormalizeScriptCov(merged); + return merged; + } + const first = scriptCovs[0]; + const scriptId = first.scriptId; + const url = first.url; + const rangeToFuncs = new Map(); + for (const scriptCov of scriptCovs) { + for (const funcCov of scriptCov.functions) { + const rootRange = stringifyFunctionRootRange(funcCov); + let funcCovs = rangeToFuncs.get(rootRange); + if (funcCovs === undefined || + // if the entry in rangeToFuncs is function-level granularity and + // the new coverage is block-level, prefer block-level. + (!funcCovs[0].isBlockCoverage && funcCov.isBlockCoverage)) { + funcCovs = []; + rangeToFuncs.set(rootRange, funcCovs); + } + else if (funcCovs[0].isBlockCoverage && !funcCov.isBlockCoverage) { + // if the entry in rangeToFuncs is block-level granularity, we should + // not append function level granularity. + continue; + } + funcCovs.push(funcCov); + } + } + const functions = []; + for (const funcCovs of rangeToFuncs.values()) { + // assert: `funcCovs.length > 0` + functions.push(mergeFunctionCovs(funcCovs)); + } + const merged = { scriptId, url, functions }; + normalizeScriptCov(merged); + return merged; +} +/** + * Returns a string representation of the root range of the function. + * + * This string can be used to match function with same root range. + * The string is derived from the start and end offsets of the root range of + * the function. + * This assumes that `ranges` is non-empty (true for valid function coverages). + * + * @param funcCov Function coverage with the range to stringify + * @internal + */ +function stringifyFunctionRootRange(funcCov) { + const rootRange = funcCov.ranges[0]; + return `${rootRange.startOffset.toString(10)};${rootRange.endOffset.toString(10)}`; +} +/** + * Merges a list of matching function coverages. + * + * Functions are matching if their root ranges have the same span. + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param funcCovs Function coverages to merge. + * @return Merged function coverage, or `undefined` if the input list was empty. + */ +export function mergeFunctionCovs(funcCovs) { + if (funcCovs.length === 0) { + return undefined; + } + else if (funcCovs.length === 1) { + const merged = funcCovs[0]; + normalizeFunctionCov(merged); + return merged; + } + const functionName = funcCovs[0].functionName; + const trees = []; + for (const funcCov of funcCovs) { + // assert: `fn.ranges.length > 0` + // assert: `fn.ranges` is sorted + trees.push(RangeTree.fromSortedRanges(funcCov.ranges)); + } + // assert: `trees.length > 0` + const mergedTree = mergeRangeTrees(trees); + normalizeRangeTree(mergedTree); + const ranges = mergedTree.toRanges(); + const isBlockCoverage = !(ranges.length === 1 && ranges[0].count === 0); + const merged = { functionName, ranges, isBlockCoverage }; + // assert: `merged` is normalized + return merged; +} +/** + * @precondition Same `start` and `end` for all the trees + */ +function mergeRangeTrees(trees) { + if (trees.length <= 1) { + return trees[0]; + } + const first = trees[0]; + let delta = 0; + for (const tree of trees) { + delta += tree.delta; + } + const children = mergeRangeTreeChildren(trees); + return new RangeTree(first.start, first.end, delta, children); +} +class RangeTreeWithParent { + constructor(parentIndex, tree) { + this.parentIndex = parentIndex; + this.tree = tree; + } +} +class StartEvent { + constructor(offset, trees) { + this.offset = offset; + this.trees = trees; + } + static compare(a, b) { + return a.offset - b.offset; + } +} +class StartEventQueue { + constructor(queue) { + this.queue = queue; + this.nextIndex = 0; + this.pendingOffset = 0; + this.pendingTrees = undefined; + } + static fromParentTrees(parentTrees) { + const startToTrees = new Map(); + for (const [parentIndex, parentTree] of parentTrees.entries()) { + for (const child of parentTree.children) { + let trees = startToTrees.get(child.start); + if (trees === undefined) { + trees = []; + startToTrees.set(child.start, trees); + } + trees.push(new RangeTreeWithParent(parentIndex, child)); + } + } + const queue = []; + for (const [startOffset, trees] of startToTrees) { + queue.push(new StartEvent(startOffset, trees)); + } + queue.sort(StartEvent.compare); + return new StartEventQueue(queue); + } + setPendingOffset(offset) { + this.pendingOffset = offset; + } + pushPendingTree(tree) { + if (this.pendingTrees === undefined) { + this.pendingTrees = []; + } + this.pendingTrees.push(tree); + } + next() { + const pendingTrees = this.pendingTrees; + const nextEvent = this.queue[this.nextIndex]; + if (pendingTrees === undefined) { + this.nextIndex++; + return nextEvent; + } + else if (nextEvent === undefined) { + this.pendingTrees = undefined; + return new StartEvent(this.pendingOffset, pendingTrees); + } + else { + if (this.pendingOffset < nextEvent.offset) { + this.pendingTrees = undefined; + return new StartEvent(this.pendingOffset, pendingTrees); + } + else { + if (this.pendingOffset === nextEvent.offset) { + this.pendingTrees = undefined; + for (const tree of pendingTrees) { + nextEvent.trees.push(tree); + } + } + this.nextIndex++; + return nextEvent; + } + } + } +} +function mergeRangeTreeChildren(parentTrees) { + const result = []; + const startEventQueue = StartEventQueue.fromParentTrees(parentTrees); + const parentToNested = new Map(); + let openRange; + while (true) { + const event = startEventQueue.next(); + if (event === undefined) { + break; + } + if (openRange !== undefined && openRange.end <= event.offset) { + result.push(nextChild(openRange, parentToNested)); + openRange = undefined; + } + if (openRange === undefined) { + let openRangeEnd = event.offset + 1; + for (const { parentIndex, tree } of event.trees) { + openRangeEnd = Math.max(openRangeEnd, tree.end); + insertChild(parentToNested, parentIndex, tree); + } + startEventQueue.setPendingOffset(openRangeEnd); + openRange = { start: event.offset, end: openRangeEnd }; + } + else { + for (const { parentIndex, tree } of event.trees) { + if (tree.end > openRange.end) { + const right = tree.split(openRange.end); + startEventQueue.pushPendingTree(new RangeTreeWithParent(parentIndex, right)); + } + insertChild(parentToNested, parentIndex, tree); + } + } + } + if (openRange !== undefined) { + result.push(nextChild(openRange, parentToNested)); + } + return result; +} +function insertChild(parentToNested, parentIndex, tree) { + let nested = parentToNested.get(parentIndex); + if (nested === undefined) { + nested = []; + parentToNested.set(parentIndex, nested); + } + nested.push(tree); +} +function nextChild(openRange, parentToNested) { + const matchingTrees = []; + for (const nested of parentToNested.values()) { + if (nested.length === 1 && nested[0].start === openRange.start && nested[0].end === openRange.end) { + matchingTrees.push(nested[0]); + } + else { + matchingTrees.push(new RangeTree(openRange.start, openRange.end, 0, nested)); + } + } + parentToNested.clear(); + return mergeRangeTrees(matchingTrees); +} + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvbWVyZ2UudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUNMLHNCQUFzQixFQUN0QixvQkFBb0IsRUFDcEIsbUJBQW1CLEVBQ25CLGtCQUFrQixFQUNsQixrQkFBa0IsR0FDbkIsTUFBTSxhQUFhLENBQUM7QUFDckIsT0FBTyxFQUFFLFNBQVMsRUFBRSxNQUFNLGNBQWMsQ0FBQztBQUd6Qzs7Ozs7Ozs7OztHQVVHO0FBQ0gsTUFBTSxVQUFVLGdCQUFnQixDQUFDLFdBQXNDO0lBQ3JFLElBQUksV0FBVyxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDNUIsT0FBTyxFQUFDLE1BQU0sRUFBRSxFQUFFLEVBQUMsQ0FBQztLQUNyQjtJQUVELE1BQU0sWUFBWSxHQUE2QixJQUFJLEdBQUcsRUFBRSxDQUFDO0lBQ3pELEtBQUssTUFBTSxVQUFVLElBQUksV0FBVyxFQUFFO1FBQ3BDLEtBQUssTUFBTSxTQUFTLElBQUksVUFBVSxDQUFDLE1BQU0sRUFBRTtZQUN6QyxJQUFJLFVBQVUsR0FBNEIsWUFBWSxDQUFDLEdBQUcsQ0FBQyxTQUFTLENBQUMsR0FBRyxDQUFDLENBQUM7WUFDMUUsSUFBSSxVQUFVLEtBQUssU0FBUyxFQUFFO2dCQUM1QixVQUFVLEdBQUcsRUFBRSxDQUFDO2dCQUNoQixZQUFZLENBQUMsR0FBRyxDQUFDLFNBQVMsQ0FBQyxHQ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lKTtcbn1cblxuZnVuY3Rpb24gbmV4dENoaWxkKG9wZW5SYW5nZTogUmFuZ2UsIHBhcmVudFRvTmVzdGVkOiBNYXA8bnVtYmVyLCBSYW5nZVRyZWVbXT4pOiBSYW5nZVRyZWUge1xuICBjb25zdCBtYXRjaGluZ1RyZWVzOiBSYW5nZVRyZWVbXSA9IFtdO1xuXG4gIGZvciAoY29uc3QgbmVzdGVkIG9mIHBhcmVudFRvTmVzdGVkLnZhbHVlcygpKSB7XG4gICAgaWYgKG5lc3RlZC5sZW5ndGggPT09IDEgJiYgbmVzdGVkWzBdLnN0YXJ0ID09PSBvcGVuUmFuZ2Uuc3RhcnQgJiYgbmVzdGVkWzBdLmVuZCA9PT0gb3BlblJhbmdlLmVuZCkge1xuICAgICAgbWF0Y2hpbmdUcmVlcy5wdXNoKG5lc3RlZFswXSk7XG4gICAgfSBlbHNlIHtcbiAgICAgIG1hdGNoaW5nVHJlZXMucHVzaChuZXcgUmFuZ2VUcmVlKFxuICAgICAgICBvcGVuUmFuZ2Uuc3RhcnQsXG4gICAgICAgIG9wZW5SYW5nZS5lbmQsXG4gICAgICAgIDAsXG4gICAgICAgIG5lc3RlZCxcbiAgICAgICkpO1xuICAgIH1cbiAgfVxuICBwYXJlbnRUb05lc3RlZC5jbGVhcigpO1xuICByZXR1cm4gbWVyZ2VSYW5nZVRyZWVzKG1hdGNoaW5nVHJlZXMpITtcbn1cbiJdLCJzb3VyY2VSb290IjoiIn0= diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/normalize.d.ts b/node_modules/@bcoe/v8-coverage/dist/lib/normalize.d.ts new file mode 100644 index 0000000..db9f0f8 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/normalize.d.ts @@ -0,0 +1,53 @@ +import { RangeTree } from "./range-tree"; +import { FunctionCov, ProcessCov, ScriptCov } from "./types"; +/** + * Normalizes a process coverage. + * + * Sorts the scripts alphabetically by `url`. + * Reassigns script ids: the script at index `0` receives `"0"`, the script at + * index `1` receives `"1"` etc. + * This does not normalize the script coverages. + * + * @param processCov Process coverage to normalize. + */ +export declare function normalizeProcessCov(processCov: ProcessCov): void; +/** + * Normalizes a process coverage deeply. + * + * Normalizes the script coverages deeply, then normalizes the process coverage + * itself. + * + * @param processCov Process coverage to normalize. + */ +export declare function deepNormalizeProcessCov(processCov: ProcessCov): void; +/** + * Normalizes a script coverage. + * + * Sorts the function by root range (pre-order sort). + * This does not normalize the function coverages. + * + * @param scriptCov Script coverage to normalize. + */ +export declare function normalizeScriptCov(scriptCov: ScriptCov): void; +/** + * Normalizes a script coverage deeply. + * + * Normalizes the function coverages deeply, then normalizes the script coverage + * itself. + * + * @param scriptCov Script coverage to normalize. + */ +export declare function deepNormalizeScriptCov(scriptCov: ScriptCov): void; +/** + * Normalizes a function coverage. + * + * Sorts the ranges (pre-order sort). + * TODO: Tree-based normalization of the ranges. + * + * @param funcCov Function coverage to normalize. + */ +export declare function normalizeFunctionCov(funcCov: FunctionCov): void; +/** + * @internal + */ +export declare function normalizeRangeTree(tree: RangeTree): void; diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/normalize.js b/node_modules/@bcoe/v8-coverage/dist/lib/normalize.js new file mode 100644 index 0000000..92df2b6 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/normalize.js @@ -0,0 +1,87 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const compare_1 = require("./compare"); +const range_tree_1 = require("./range-tree"); +/** + * Normalizes a process coverage. + * + * Sorts the scripts alphabetically by `url`. + * Reassigns script ids: the script at index `0` receives `"0"`, the script at + * index `1` receives `"1"` etc. + * This does not normalize the script coverages. + * + * @param processCov Process coverage to normalize. + */ +function normalizeProcessCov(processCov) { + processCov.result.sort(compare_1.compareScriptCovs); + for (const [scriptId, scriptCov] of processCov.result.entries()) { + scriptCov.scriptId = scriptId.toString(10); + } +} +exports.normalizeProcessCov = normalizeProcessCov; +/** + * Normalizes a process coverage deeply. + * + * Normalizes the script coverages deeply, then normalizes the process coverage + * itself. + * + * @param processCov Process coverage to normalize. + */ +function deepNormalizeProcessCov(processCov) { + for (const scriptCov of processCov.result) { + deepNormalizeScriptCov(scriptCov); + } + normalizeProcessCov(processCov); +} +exports.deepNormalizeProcessCov = deepNormalizeProcessCov; +/** + * Normalizes a script coverage. + * + * Sorts the function by root range (pre-order sort). + * This does not normalize the function coverages. + * + * @param scriptCov Script coverage to normalize. + */ +function normalizeScriptCov(scriptCov) { + scriptCov.functions.sort(compare_1.compareFunctionCovs); +} +exports.normalizeScriptCov = normalizeScriptCov; +/** + * Normalizes a script coverage deeply. + * + * Normalizes the function coverages deeply, then normalizes the script coverage + * itself. + * + * @param scriptCov Script coverage to normalize. + */ +function deepNormalizeScriptCov(scriptCov) { + for (const funcCov of scriptCov.functions) { + normalizeFunctionCov(funcCov); + } + normalizeScriptCov(scriptCov); +} +exports.deepNormalizeScriptCov = deepNormalizeScriptCov; +/** + * Normalizes a function coverage. + * + * Sorts the ranges (pre-order sort). + * TODO: Tree-based normalization of the ranges. + * + * @param funcCov Function coverage to normalize. + */ +function normalizeFunctionCov(funcCov) { + funcCov.ranges.sort(compare_1.compareRangeCovs); + const tree = range_tree_1.RangeTree.fromSortedRanges(funcCov.ranges); + normalizeRangeTree(tree); + funcCov.ranges = tree.toRanges(); +} +exports.normalizeFunctionCov = normalizeFunctionCov; +/** + * @internal + */ +function normalizeRangeTree(tree) { + tree.normalize(); +} +exports.normalizeRangeTree = normalizeRangeTree; + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvbm9ybWFsaXplLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQXFGO0FBQ3JGLDZDQUF5QztBQUd6Qzs7Ozs7Ozs7O0dBU0c7QUFDSCxTQUFnQixtQkFBbUIsQ0FBQyxVQUFzQjtJQUN4RCxVQUFVLENBQUMsTUFBTSxDQUFDLElBQUksQ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5jQ292IEZ1bmN0aW9uIGNvdmVyYWdlIHRvIG5vcm1hbGl6ZS5cbiAqL1xuZXhwb3J0IGZ1bmN0aW9uIG5vcm1hbGl6ZUZ1bmN0aW9uQ292KGZ1bmNDb3Y6IEZ1bmN0aW9uQ292KTogdm9pZCB7XG4gIGZ1bmNDb3YucmFuZ2VzLnNvcnQoY29tcGFyZVJhbmdlQ292cyk7XG4gIGNvbnN0IHRyZWU6IFJhbmdlVHJlZSA9IFJhbmdlVHJlZS5mcm9tU29ydGVkUmFuZ2VzKGZ1bmNDb3YucmFuZ2VzKSE7XG4gIG5vcm1hbGl6ZVJhbmdlVHJlZSh0cmVlKTtcbiAgZnVuY0Nvdi5yYW5nZXMgPSB0cmVlLnRvUmFuZ2VzKCk7XG59XG5cbi8qKlxuICogQGludGVybmFsXG4gKi9cbmV4cG9ydCBmdW5jdGlvbiBub3JtYWxpemVSYW5nZVRyZWUodHJlZTogUmFuZ2VUcmVlKTogdm9pZCB7XG4gIHRyZWUubm9ybWFsaXplKCk7XG59XG4iXSwic291cmNlUm9vdCI6IiJ9 diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/normalize.mjs b/node_modules/@bcoe/v8-coverage/dist/lib/normalize.mjs new file mode 100644 index 0000000..2c477eb --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/normalize.mjs @@ -0,0 +1,79 @@ +import { compareFunctionCovs, compareRangeCovs, compareScriptCovs } from "./compare"; +import { RangeTree } from "./range-tree"; +/** + * Normalizes a process coverage. + * + * Sorts the scripts alphabetically by `url`. + * Reassigns script ids: the script at index `0` receives `"0"`, the script at + * index `1` receives `"1"` etc. + * This does not normalize the script coverages. + * + * @param processCov Process coverage to normalize. + */ +export function normalizeProcessCov(processCov) { + processCov.result.sort(compareScriptCovs); + for (const [scriptId, scriptCov] of processCov.result.entries()) { + scriptCov.scriptId = scriptId.toString(10); + } +} +/** + * Normalizes a process coverage deeply. + * + * Normalizes the script coverages deeply, then normalizes the process coverage + * itself. + * + * @param processCov Process coverage to normalize. + */ +export function deepNormalizeProcessCov(processCov) { + for (const scriptCov of processCov.result) { + deepNormalizeScriptCov(scriptCov); + } + normalizeProcessCov(processCov); +} +/** + * Normalizes a script coverage. + * + * Sorts the function by root range (pre-order sort). + * This does not normalize the function coverages. + * + * @param scriptCov Script coverage to normalize. + */ +export function normalizeScriptCov(scriptCov) { + scriptCov.functions.sort(compareFunctionCovs); +} +/** + * Normalizes a script coverage deeply. + * + * Normalizes the function coverages deeply, then normalizes the script coverage + * itself. + * + * @param scriptCov Script coverage to normalize. + */ +export function deepNormalizeScriptCov(scriptCov) { + for (const funcCov of scriptCov.functions) { + normalizeFunctionCov(funcCov); + } + normalizeScriptCov(scriptCov); +} +/** + * Normalizes a function coverage. + * + * Sorts the ranges (pre-order sort). + * TODO: Tree-based normalization of the ranges. + * + * @param funcCov Function coverage to normalize. + */ +export function normalizeFunctionCov(funcCov) { + funcCov.ranges.sort(compareRangeCovs); + const tree = RangeTree.fromSortedRanges(funcCov.ranges); + normalizeRangeTree(tree); + funcCov.ranges = tree.toRanges(); +} +/** + * @internal + */ +export function normalizeRangeTree(tree) { + tree.normalize(); +} + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvbm9ybWFsaXplLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFBRSxtQkFBbUIsRUFBRSxnQkFBZ0IsRUFBRSxpQkFBaUIsRUFBRSxNQUFNLFdBQVcsQ0FBQztBQUNyRixPQUFPLEVBQUUsU0FBUyxFQUFFLE1BQU0sY0FBYyxDQUFDO0FBR3pDOzs7Ozs7Ozs7R0FTRztBQUNILE1BQU0sVUFBVSxtQkFBbUIsQ0FBQyxVQUFzQjtJQUN4RCxVQUFVLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxpQkFBaUIsQ0FBQyxDQUFDO0lBQzFDLEtBQUssTUFBTSxDQ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GdW5jdGlvbkNvdik6IHZvaWQge1xuICBmdW5jQ292LnJhbmdlcy5zb3J0KGNvbXBhcmVSYW5nZUNvdnMpO1xuICBjb25zdCB0cmVlOiBSYW5nZVRyZWUgPSBSYW5nZVRyZWUuZnJvbVNvcnRlZFJhbmdlcyhmdW5jQ292LnJhbmdlcykhO1xuICBub3JtYWxpemVSYW5nZVRyZWUodHJlZSk7XG4gIGZ1bmNDb3YucmFuZ2VzID0gdHJlZS50b1JhbmdlcygpO1xufVxuXG4vKipcbiAqIEBpbnRlcm5hbFxuICovXG5leHBvcnQgZnVuY3Rpb24gbm9ybWFsaXplUmFuZ2VUcmVlKHRyZWU6IFJhbmdlVHJlZSk6IHZvaWQge1xuICB0cmVlLm5vcm1hbGl6ZSgpO1xufVxuIl0sInNvdXJjZVJvb3QiOiIifQ== diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/package.json b/node_modules/@bcoe/v8-coverage/dist/lib/package.json new file mode 100644 index 0000000..d81b33c --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/package.json @@ -0,0 +1,44 @@ +{ + "name": "@bcoe/v8-coverage", + "version": "0.2.3", + "description": "Helper functions for V8 coverage files.", + "author": "Charles Samborski (https://demurgos.net)", + "license": "MIT", + "main": "index", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/demurgos/v8-coverage.git" + }, + "homepage": "https://demurgos.github.io/v8-coverage", + "devDependencies": { + "@types/chai": "^4.1.4", + "@types/gulp": "^4.0.5", + "@types/minimist": "^1.2.0", + "@types/mocha": "^5.2.2", + "@types/node": "^10.5.4", + "chai": "^4.1.2", + "codecov": "^3.0.2", + "gulp": "^4.0.0", + "gulp-cli": "^2.0.1", + "minimist": "^1.2.0", + "pre-commit": "^1.2.2", + "ts-node": "^8.3.0", + "turbo-gulp": "^0.20.1" + }, + "nyc": { + "include": [ + "build/test/lib/**/*.js", + "build/test/lib/**/*.mjs" + ], + "reporter": [ + "text", + "html" + ], + "extension": [ + ".mjs" + ] + }, + "gitHead": "529387e2bd3e0ba0b9336d80ec563aee593331e1", + "private": false +} \ No newline at end of file diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/range-tree.d.ts b/node_modules/@bcoe/v8-coverage/dist/lib/range-tree.d.ts new file mode 100644 index 0000000..f7e18e8 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/range-tree.d.ts @@ -0,0 +1,24 @@ +import { RangeCov } from "./types"; +export declare class RangeTree { + start: number; + end: number; + delta: number; + children: RangeTree[]; + constructor(start: number, end: number, delta: number, children: RangeTree[]); + /** + * @precodition `ranges` are well-formed and pre-order sorted + */ + static fromSortedRanges(ranges: ReadonlyArray): RangeTree | undefined; + normalize(): void; + /** + * @precondition `tree.start < value && value < tree.end` + * @return RangeTree Right part + */ + split(value: number): RangeTree; + /** + * Get the range coverages corresponding to the tree. + * + * The ranges are pre-order sorted. + */ + toRanges(): RangeCov[]; +} diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/range-tree.js b/node_modules/@bcoe/v8-coverage/dist/lib/range-tree.js new file mode 100644 index 0000000..f392cf1 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/range-tree.js @@ -0,0 +1,139 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +class RangeTree { + constructor(start, end, delta, children) { + this.start = start; + this.end = end; + this.delta = delta; + this.children = children; + } + /** + * @precodition `ranges` are well-formed and pre-order sorted + */ + static fromSortedRanges(ranges) { + let root; + // Stack of parent trees and parent counts. + const stack = []; + for (const range of ranges) { + const node = new RangeTree(range.startOffset, range.endOffset, range.count, []); + if (root === undefined) { + root = node; + stack.push([node, range.count]); + continue; + } + let parent; + let parentCount; + while (true) { + [parent, parentCount] = stack[stack.length - 1]; + // assert: `top !== undefined` (the ranges are sorted) + if (range.startOffset < parent.end) { + break; + } + else { + stack.pop(); + } + } + node.delta -= parentCount; + parent.children.push(node); + stack.push([node, range.count]); + } + return root; + } + normalize() { + const children = []; + let curEnd; + let head; + const tail = []; + for (const child of this.children) { + if (head === undefined) { + head = child; + } + else if (child.delta === head.delta && child.start === curEnd) { + tail.push(child); + } + else { + endChain(); + head = child; + } + curEnd = child.end; + } + if (head !== undefined) { + endChain(); + } + if (children.length === 1) { + const child = children[0]; + if (child.start === this.start && child.end === this.end) { + this.delta += child.delta; + this.children = child.children; + // `.lazyCount` is zero for both (both are after normalization) + return; + } + } + this.children = children; + function endChain() { + if (tail.length !== 0) { + head.end = tail[tail.length - 1].end; + for (const tailTree of tail) { + for (const subChild of tailTree.children) { + subChild.delta += tailTree.delta - head.delta; + head.children.push(subChild); + } + } + tail.length = 0; + } + head.normalize(); + children.push(head); + } + } + /** + * @precondition `tree.start < value && value < tree.end` + * @return RangeTree Right part + */ + split(value) { + let leftChildLen = this.children.length; + let mid; + // TODO(perf): Binary search (check overhead) + for (let i = 0; i < this.children.length; i++) { + const child = this.children[i]; + if (child.start < value && value < child.end) { + mid = child.split(value); + leftChildLen = i + 1; + break; + } + else if (child.start >= value) { + leftChildLen = i; + break; + } + } + const rightLen = this.children.length - leftChildLen; + const rightChildren = this.children.splice(leftChildLen, rightLen); + if (mid !== undefined) { + rightChildren.unshift(mid); + } + const result = new RangeTree(value, this.end, this.delta, rightChildren); + this.end = value; + return result; + } + /** + * Get the range coverages corresponding to the tree. + * + * The ranges are pre-order sorted. + */ + toRanges() { + const ranges = []; + // Stack of parent trees and counts. + const stack = [[this, 0]]; + while (stack.length > 0) { + const [cur, parentCount] = stack.pop(); + const count = parentCount + cur.delta; + ranges.push({ startOffset: cur.start, endOffset: cur.end, count }); + for (let i = cur.children.length - 1; i >= 0; i--) { + stack.push([cur.children[i], count]); + } + } + return ranges; + } +} +exports.RangeTree = RangeTree; + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvcmFuZ2UtdHJlZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBLE1BQWEsU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HJlZSwgbnVtYmVyXVtdID0gW1t0aGlzLCAwXV07XG4gICAgd2hpbGUgKHN0YWNrLmxlbmd0aCA+IDApIHtcbiAgICAgIGNvbnN0IFtjdXIsIHBhcmVudENvdW50XTogW1JhbmdlVHJlZSwgbnVtYmVyXSA9IHN0YWNrLnBvcCgpITtcbiAgICAgIGNvbnN0IGNvdW50OiBudW1iZXIgPSBwYXJlbnRDb3VudCArIGN1ci5kZWx0YTtcbiAgICAgIHJhbmdlcy5wdXNoKHtzdGFydE9mZnNldDogY3VyLnN0YXJ0LCBlbmRPZmZzZXQ6IGN1ci5lbmQsIGNvdW50fSk7XG4gICAgICBmb3IgKGxldCBpOiBudW1iZXIgPSBjdXIuY2hpbGRyZW4ubGVuZ3RoIC0gMTsgaSA+PSAwOyBpLS0pIHtcbiAgICAgICAgc3RhY2sucHVzaChbY3VyLmNoaWxkcmVuW2ldLCBjb3VudF0pO1xuICAgICAgfVxuICAgIH1cbiAgICByZXR1cm4gcmFuZ2VzO1xuICB9XG59XG4iXSwic291cmNlUm9vdCI6IiJ9 diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/range-tree.mjs b/node_modules/@bcoe/v8-coverage/dist/lib/range-tree.mjs new file mode 100644 index 0000000..73f13dd --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/range-tree.mjs @@ -0,0 +1,136 @@ +export class RangeTree { + constructor(start, end, delta, children) { + this.start = start; + this.end = end; + this.delta = delta; + this.children = children; + } + /** + * @precodition `ranges` are well-formed and pre-order sorted + */ + static fromSortedRanges(ranges) { + let root; + // Stack of parent trees and parent counts. + const stack = []; + for (const range of ranges) { + const node = new RangeTree(range.startOffset, range.endOffset, range.count, []); + if (root === undefined) { + root = node; + stack.push([node, range.count]); + continue; + } + let parent; + let parentCount; + while (true) { + [parent, parentCount] = stack[stack.length - 1]; + // assert: `top !== undefined` (the ranges are sorted) + if (range.startOffset < parent.end) { + break; + } + else { + stack.pop(); + } + } + node.delta -= parentCount; + parent.children.push(node); + stack.push([node, range.count]); + } + return root; + } + normalize() { + const children = []; + let curEnd; + let head; + const tail = []; + for (const child of this.children) { + if (head === undefined) { + head = child; + } + else if (child.delta === head.delta && child.start === curEnd) { + tail.push(child); + } + else { + endChain(); + head = child; + } + curEnd = child.end; + } + if (head !== undefined) { + endChain(); + } + if (children.length === 1) { + const child = children[0]; + if (child.start === this.start && child.end === this.end) { + this.delta += child.delta; + this.children = child.children; + // `.lazyCount` is zero for both (both are after normalization) + return; + } + } + this.children = children; + function endChain() { + if (tail.length !== 0) { + head.end = tail[tail.length - 1].end; + for (const tailTree of tail) { + for (const subChild of tailTree.children) { + subChild.delta += tailTree.delta - head.delta; + head.children.push(subChild); + } + } + tail.length = 0; + } + head.normalize(); + children.push(head); + } + } + /** + * @precondition `tree.start < value && value < tree.end` + * @return RangeTree Right part + */ + split(value) { + let leftChildLen = this.children.length; + let mid; + // TODO(perf): Binary search (check overhead) + for (let i = 0; i < this.children.length; i++) { + const child = this.children[i]; + if (child.start < value && value < child.end) { + mid = child.split(value); + leftChildLen = i + 1; + break; + } + else if (child.start >= value) { + leftChildLen = i; + break; + } + } + const rightLen = this.children.length - leftChildLen; + const rightChildren = this.children.splice(leftChildLen, rightLen); + if (mid !== undefined) { + rightChildren.unshift(mid); + } + const result = new RangeTree(value, this.end, this.delta, rightChildren); + this.end = value; + return result; + } + /** + * Get the range coverages corresponding to the tree. + * + * The ranges are pre-order sorted. + */ + toRanges() { + const ranges = []; + // Stack of parent trees and counts. + const stack = [[this, 0]]; + while (stack.length > 0) { + const [cur, parentCount] = stack.pop(); + const count = parentCount + cur.delta; + ranges.push({ startOffset: cur.start, endOffset: cur.end, count }); + for (let i = cur.children.length - 1; i >= 0; i--) { + stack.push([cur.children[i], count]); + } + } + return ranges; + } +} + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvcmFuZ2UtdHJlZS50cyJdLCJuYW1lcyI6W10sIm1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mFuZ2VUcmVlLCBudW1iZXJdW10gPSBbW3RoaXMsIDBdXTtcbiAgICB3aGlsZSAoc3RhY2subGVuZ3RoID4gMCkge1xuICAgICAgY29uc3QgW2N1ciwgcGFyZW50Q291bnRdOiBbUmFuZ2VUcmVlLCBudW1iZXJdID0gc3RhY2sucG9wKCkhO1xuICAgICAgY29uc3QgY291bnQ6IG51bWJlciA9IHBhcmVudENvdW50ICsgY3VyLmRlbHRhO1xuICAgICAgcmFuZ2VzLnB1c2goe3N0YXJ0T2Zmc2V0OiBjdXIuc3RhcnQsIGVuZE9mZnNldDogY3VyLmVuZCwgY291bnR9KTtcbiAgICAgIGZvciAobGV0IGk6IG51bWJlciA9IGN1ci5jaGlsZHJlbi5sZW5ndGggLSAxOyBpID49IDA7IGktLSkge1xuICAgICAgICBzdGFjay5wdXNoKFtjdXIuY2hpbGRyZW5baV0sIGNvdW50XSk7XG4gICAgICB9XG4gICAgfVxuICAgIHJldHVybiByYW5nZXM7XG4gIH1cbn1cbiJdLCJzb3VyY2VSb290IjoiIn0= diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/tsconfig.json b/node_modules/@bcoe/v8-coverage/dist/lib/tsconfig.json new file mode 100644 index 0000000..aff36e9 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/tsconfig.json @@ -0,0 +1,62 @@ +{ + "compilerOptions": { + "allowJs": false, + "allowSyntheticDefaultImports": true, + "allowUnreachableCode": false, + "allowUnusedLabels": false, + "alwaysStrict": true, + "charset": "utf8", + "checkJs": false, + "declaration": true, + "disableSizeLimit": false, + "downlevelIteration": false, + "emitBOM": false, + "emitDecoratorMetadata": true, + "esModuleInterop": true, + "experimentalDecorators": true, + "forceConsistentCasingInFileNames": true, + "importHelpers": false, + "inlineSourceMap": false, + "inlineSources": false, + "isolatedModules": false, + "lib": [ + "es2017", + "esnext.asynciterable" + ], + "locale": "en-us", + "module": "commonjs", + "moduleResolution": "node", + "newLine": "lf", + "noEmit": false, + "noEmitHelpers": false, + "noEmitOnError": true, + "noErrorTruncation": true, + "noFallthroughCasesInSwitch": true, + "noImplicitAny": true, + "noImplicitReturns": true, + "noImplicitThis": true, + "noStrictGenericChecks": false, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitUseStrict": false, + "noLib": false, + "noResolve": false, + "preserveConstEnums": true, + "removeComments": false, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "strictNullChecks": true, + "suppressExcessPropertyErrors": false, + "suppressImplicitAnyIndexErrors": false, + "target": "es2017", + "traceResolution": false, + "rootDir": "", + "outDir": "../../build/lib", + "typeRoots": [] + }, + "include": [ + "**/*.ts" + ], + "exclude": [] +} diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/types.d.ts b/node_modules/@bcoe/v8-coverage/dist/lib/types.d.ts new file mode 100644 index 0000000..1d44190 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/types.d.ts @@ -0,0 +1,22 @@ +export interface ProcessCov { + result: ScriptCov[]; +} +export interface ScriptCov { + scriptId: string; + url: string; + functions: FunctionCov[]; +} +export interface FunctionCov { + functionName: string; + ranges: RangeCov[]; + isBlockCoverage: boolean; +} +export interface Range { + readonly start: number; + readonly end: number; +} +export interface RangeCov { + startOffset: number; + endOffset: number; + count: number; +} diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/types.js b/node_modules/@bcoe/v8-coverage/dist/lib/types.js new file mode 100644 index 0000000..9f4533d --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/types.js @@ -0,0 +1,4 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvdHlwZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJ0eXBlcy5qcyIsInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBpbnRlcmZhY2UgUHJvY2Vzc0NvdiB7XG4gIHJlc3VsdDogU2NyaXB0Q292W107XG59XG5cbmV4cG9ydCBpbnRlcmZhY2UgU2NyaXB0Q292IHtcbiAgc2NyaXB0SWQ6IHN0cmluZztcbiAgdXJsOiBzdHJpbmc7XG4gIGZ1bmN0aW9uczogRnVuY3Rpb25Db3ZbXTtcbn1cblxuZXhwb3J0IGludGVyZmFjZSBGdW5jdGlvbkNvdiB7XG4gIGZ1bmN0aW9uTmFtZTogc3RyaW5nO1xuICByYW5nZXM6IFJhbmdlQ292W107XG4gIGlzQmxvY2tDb3ZlcmFnZTogYm9vbGVhbjtcbn1cblxuZXhwb3J0IGludGVyZmFjZSBSYW5nZSB7XG4gIHJlYWRvbmx5IHN0YXJ0OiBudW1iZXI7XG4gIHJlYWRvbmx5IGVuZDogbnVtYmVyO1xufVxuXG5leHBvcnQgaW50ZXJmYWNlIFJhbmdlQ292IHtcbiAgc3RhcnRPZmZzZXQ6IG51bWJlcjtcbiAgZW5kT2Zmc2V0OiBudW1iZXI7XG4gIGNvdW50OiBudW1iZXI7XG59XG4iXSwic291cmNlUm9vdCI6IiJ9 diff --git a/node_modules/@bcoe/v8-coverage/dist/lib/types.mjs b/node_modules/@bcoe/v8-coverage/dist/lib/types.mjs new file mode 100644 index 0000000..d5b9746 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/dist/lib/types.mjs @@ -0,0 +1,3 @@ + + +//# sourceMappingURL=data:application/json;charset=utf8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIl9zcmMvdHlwZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiJ0eXBlcy5qcyIsInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBpbnRlcmZhY2UgUHJvY2Vzc0NvdiB7XG4gIHJlc3VsdDogU2NyaXB0Q292W107XG59XG5cbmV4cG9ydCBpbnRlcmZhY2UgU2NyaXB0Q292IHtcbiAgc2NyaXB0SWQ6IHN0cmluZztcbiAgdXJsOiBzdHJpbmc7XG4gIGZ1bmN0aW9uczogRnVuY3Rpb25Db3ZbXTtcbn1cblxuZXhwb3J0IGludGVyZmFjZSBGdW5jdGlvbkNvdiB7XG4gIGZ1bmN0aW9uTmFtZTogc3RyaW5nO1xuICByYW5nZXM6IFJhbmdlQ292W107XG4gIGlzQmxvY2tDb3ZlcmFnZTogYm9vbGVhbjtcbn1cblxuZXhwb3J0IGludGVyZmFjZSBSYW5nZSB7XG4gIHJlYWRvbmx5IHN0YXJ0OiBudW1iZXI7XG4gIHJlYWRvbmx5IGVuZDogbnVtYmVyO1xufVxuXG5leHBvcnQgaW50ZXJmYWNlIFJhbmdlQ292IHtcbiAgc3RhcnRPZmZzZXQ6IG51bWJlcjtcbiAgZW5kT2Zmc2V0OiBudW1iZXI7XG4gIGNvdW50OiBudW1iZXI7XG59XG4iXSwic291cmNlUm9vdCI6IiJ9 diff --git a/node_modules/@bcoe/v8-coverage/gulpfile.ts b/node_modules/@bcoe/v8-coverage/gulpfile.ts new file mode 100644 index 0000000..cdcfc81 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/gulpfile.ts @@ -0,0 +1,95 @@ +import * as buildTools from "turbo-gulp"; +import { LibTarget, registerLibTasks } from "turbo-gulp/targets/lib"; +import { MochaTarget, registerMochaTasks } from "turbo-gulp/targets/mocha"; + +import gulp from "gulp"; +import minimist from "minimist"; + +interface Options { + devDist?: string; +} + +const options: Options & minimist.ParsedArgs = minimist(process.argv.slice(2), { + string: ["devDist"], + default: {devDist: undefined}, + alias: {devDist: "dev-dist"}, +}); + +const project: buildTools.Project = { + root: __dirname, + packageJson: "package.json", + buildDir: "build", + distDir: "dist", + srcDir: "src", + typescript: {} +}; + +const lib: LibTarget = { + project, + name: "lib", + srcDir: "src/lib", + scripts: ["**/*.ts"], + mainModule: "index", + dist: { + packageJsonMap: (old: buildTools.PackageJson): buildTools.PackageJson => { + const version: string = options.devDist !== undefined ? `${old.version}-build.${options.devDist}` : old.version; + return {...old, version, scripts: undefined, private: false}; + }, + npmPublish: { + tag: options.devDist !== undefined ? "next" : "latest", + }, + }, + tscOptions: { + declaration: true, + skipLibCheck: true, + }, + typedoc: { + dir: "typedoc", + name: "Helpers for V8 coverage files", + deploy: { + repository: "git@github.com:demurgos/v8-coverage.git", + branch: "gh-pages", + }, + }, + copy: [ + { + files: ["**/*.json"], + }, + ], + clean: { + dirs: ["build/lib", "dist/lib"], + }, +}; + +const test: MochaTarget = { + project, + name: "test", + srcDir: "src", + scripts: ["test/**/*.ts", "lib/**/*.ts", "e2e/*/*.ts"], + customTypingsDir: "src/custom-typings", + tscOptions: { + allowSyntheticDefaultImports: true, + esModuleInterop: true, + skipLibCheck: true, + }, + // generateTestMain: true, + copy: [ + { + src: "e2e", + // /(project|test-resources)/ + files: ["*/project/**/*", "*/test-resources/**/*"], + dest: "e2e", + }, + ], + clean: { + dirs: ["build/test"], + }, +}; + +const libTasks: any = registerLibTasks(gulp, lib); +registerMochaTasks(gulp, test); +buildTools.projectTasks.registerAll(gulp, project); + +gulp.task("all:tsconfig.json", gulp.parallel("lib:tsconfig.json", "test:tsconfig.json")); +gulp.task("dist", libTasks.dist); +gulp.task("default", libTasks.dist); diff --git a/node_modules/@bcoe/v8-coverage/package.json b/node_modules/@bcoe/v8-coverage/package.json new file mode 100644 index 0000000..abc28b7 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/package.json @@ -0,0 +1,48 @@ +{ + "name": "@bcoe/v8-coverage", + "version": "0.2.3", + "description": "Helper functions for V8 coverage files.", + "author": "Charles Samborski (https://demurgos.net)", + "license": "MIT", + "main": "dist/lib/index", + "types": "dist/lib/index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/demurgos/v8-coverage.git" + }, + "homepage": "https://demurgos.github.io/v8-coverage", + "scripts": { + "prepare": "gulp all:tsconfig.json && gulp dist", + "pretest": "gulp lib:build", + "test": "gulp test", + "lint": "gulp :lint:fix" + }, + "devDependencies": { + "@types/chai": "^4.1.4", + "@types/gulp": "^4.0.5", + "@types/minimist": "^1.2.0", + "@types/mocha": "^5.2.2", + "@types/node": "^10.5.4", + "chai": "^4.1.2", + "codecov": "^3.0.2", + "gulp": "^4.0.0", + "gulp-cli": "^2.0.1", + "minimist": "^1.2.0", + "pre-commit": "^1.2.2", + "ts-node": "^8.3.0", + "turbo-gulp": "^0.20.1" + }, + "nyc": { + "include": [ + "build/test/lib/**/*.js", + "build/test/lib/**/*.mjs" + ], + "reporter": [ + "text", + "html" + ], + "extension": [ + ".mjs" + ] + } +} diff --git a/node_modules/@bcoe/v8-coverage/src/lib/ascii.ts b/node_modules/@bcoe/v8-coverage/src/lib/ascii.ts new file mode 100644 index 0000000..5a52b91 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/src/lib/ascii.ts @@ -0,0 +1,146 @@ +import { compareRangeCovs } from "./compare"; +import { RangeCov } from "./types"; + +interface ReadonlyRangeTree { + readonly start: number; + readonly end: number; + readonly count: number; + readonly children: ReadonlyRangeTree[]; +} + +export function emitForest(trees: ReadonlyArray): string { + return emitForestLines(trees).join("\n"); +} + +export function emitForestLines(trees: ReadonlyArray): string[] { + const colMap: Map = getColMap(trees); + const header: string = emitOffsets(colMap); + return [header, ...trees.map(tree => emitTree(tree, colMap).join("\n"))]; +} + +function getColMap(trees: Iterable): Map { + const eventSet: Set = new Set(); + for (const tree of trees) { + const stack: ReadonlyRangeTree[] = [tree]; + while (stack.length > 0) { + const cur: ReadonlyRangeTree = stack.pop()!; + eventSet.add(cur.start); + eventSet.add(cur.end); + for (const child of cur.children) { + stack.push(child); + } + } + } + const events: number[] = [...eventSet]; + events.sort((a, b) => a - b); + let maxDigits: number = 1; + for (const event of events) { + maxDigits = Math.max(maxDigits, event.toString(10).length); + } + const colWidth: number = maxDigits + 3; + const colMap: Map = new Map(); + for (const [i, event] of events.entries()) { + colMap.set(event, i * colWidth); + } + return colMap; +} + +function emitTree(tree: ReadonlyRangeTree, colMap: Map): string[] { + const layers: ReadonlyRangeTree[][] = []; + let nextLayer: ReadonlyRangeTree[] = [tree]; + while (nextLayer.length > 0) { + const layer: ReadonlyRangeTree[] = nextLayer; + layers.push(layer); + nextLayer = []; + for (const node of layer) { + for (const child of node.children) { + nextLayer.push(child); + } + } + } + return layers.map(layer => emitTreeLayer(layer, colMap)); +} + +export function parseFunctionRanges(text: string, offsetMap: Map): RangeCov[] { + const result: RangeCov[] = []; + for (const line of text.split("\n")) { + for (const range of parseTreeLayer(line, offsetMap)) { + result.push(range); + } + } + result.sort(compareRangeCovs); + return result; +} + +/** + * + * @param layer Sorted list of disjoint trees. + * @param colMap + */ +function emitTreeLayer(layer: ReadonlyRangeTree[], colMap: Map): string { + const line: string[] = []; + let curIdx: number = 0; + for (const {start, end, count} of layer) { + const startIdx: number = colMap.get(start)!; + const endIdx: number = colMap.get(end)!; + if (startIdx > curIdx) { + line.push(" ".repeat(startIdx - curIdx)); + } + line.push(emitRange(count, endIdx - startIdx)); + curIdx = endIdx; + } + return line.join(""); +} + +function parseTreeLayer(text: string, offsetMap: Map): RangeCov[] { + const result: RangeCov[] = []; + const regex: RegExp = /\[(\d+)-*\)/gs; + while (true) { + const match: RegExpMatchArray | null = regex.exec(text); + if (match === null) { + break; + } + const startIdx: number = match.index!; + const endIdx: number = startIdx + match[0].length; + const count: number = parseInt(match[1], 10); + const startOffset: number | undefined = offsetMap.get(startIdx); + const endOffset: number | undefined = offsetMap.get(endIdx); + if (startOffset === undefined || endOffset === undefined) { + throw new Error(`Invalid offsets for: ${JSON.stringify(text)}`); + } + result.push({startOffset, endOffset, count}); + } + return result; +} + +function emitRange(count: number, len: number): string { + const rangeStart: string = `[${count.toString(10)}`; + const rangeEnd: string = ")"; + const hyphensLen: number = len - (rangeStart.length + rangeEnd.length); + const hyphens: string = "-".repeat(Math.max(0, hyphensLen)); + return `${rangeStart}${hyphens}${rangeEnd}`; +} + +function emitOffsets(colMap: Map): string { + let line: string = ""; + for (const [event, col] of colMap) { + if (line.length < col) { + line += " ".repeat(col - line.length); + } + line += event.toString(10); + } + return line; +} + +export function parseOffsets(text: string): Map { + const result: Map = new Map(); + const regex: RegExp = /\d+/gs; + while (true) { + const match: RegExpExecArray | null = regex.exec(text); + if (match === null) { + break; + } + result.set(match.index, parseInt(match[0], 10)); + } + return result; +} diff --git a/node_modules/@bcoe/v8-coverage/src/lib/clone.ts b/node_modules/@bcoe/v8-coverage/src/lib/clone.ts new file mode 100644 index 0000000..1a91019 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/src/lib/clone.ts @@ -0,0 +1,70 @@ +import { FunctionCov, ProcessCov, RangeCov, ScriptCov } from "./types"; + +/** + * Creates a deep copy of a process coverage. + * + * @param processCov Process coverage to clone. + * @return Cloned process coverage. + */ +export function cloneProcessCov(processCov: Readonly): ProcessCov { + const result: ScriptCov[] = []; + for (const scriptCov of processCov.result) { + result.push(cloneScriptCov(scriptCov)); + } + + return { + result, + }; +} + +/** + * Creates a deep copy of a script coverage. + * + * @param scriptCov Script coverage to clone. + * @return Cloned script coverage. + */ +export function cloneScriptCov(scriptCov: Readonly): ScriptCov { + const functions: FunctionCov[] = []; + for (const functionCov of scriptCov.functions) { + functions.push(cloneFunctionCov(functionCov)); + } + + return { + scriptId: scriptCov.scriptId, + url: scriptCov.url, + functions, + }; +} + +/** + * Creates a deep copy of a function coverage. + * + * @param functionCov Function coverage to clone. + * @return Cloned function coverage. + */ +export function cloneFunctionCov(functionCov: Readonly): FunctionCov { + const ranges: RangeCov[] = []; + for (const rangeCov of functionCov.ranges) { + ranges.push(cloneRangeCov(rangeCov)); + } + + return { + functionName: functionCov.functionName, + ranges, + isBlockCoverage: functionCov.isBlockCoverage, + }; +} + +/** + * Creates a deep copy of a function coverage. + * + * @param rangeCov Range coverage to clone. + * @return Cloned range coverage. + */ +export function cloneRangeCov(rangeCov: Readonly): RangeCov { + return { + startOffset: rangeCov.startOffset, + endOffset: rangeCov.endOffset, + count: rangeCov.count, + }; +} diff --git a/node_modules/@bcoe/v8-coverage/src/lib/compare.ts b/node_modules/@bcoe/v8-coverage/src/lib/compare.ts new file mode 100644 index 0000000..8f5614c --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/src/lib/compare.ts @@ -0,0 +1,40 @@ +import { FunctionCov, RangeCov, ScriptCov } from "./types"; + +/** + * Compares two script coverages. + * + * The result corresponds to the comparison of their `url` value (alphabetical sort). + */ +export function compareScriptCovs(a: Readonly, b: Readonly): number { + if (a.url === b.url) { + return 0; + } else if (a.url < b.url) { + return -1; + } else { + return 1; + } +} + +/** + * Compares two function coverages. + * + * The result corresponds to the comparison of the root ranges. + */ +export function compareFunctionCovs(a: Readonly, b: Readonly): number { + return compareRangeCovs(a.ranges[0], b.ranges[0]); +} + +/** + * Compares two range coverages. + * + * The ranges are first ordered by ascending `startOffset` and then by + * descending `endOffset`. + * This corresponds to a pre-order tree traversal. + */ +export function compareRangeCovs(a: Readonly, b: Readonly): number { + if (a.startOffset !== b.startOffset) { + return a.startOffset - b.startOffset; + } else { + return b.endOffset - a.endOffset; + } +} diff --git a/node_modules/@bcoe/v8-coverage/src/lib/index.ts b/node_modules/@bcoe/v8-coverage/src/lib/index.ts new file mode 100644 index 0000000..f92bdf3 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/src/lib/index.ts @@ -0,0 +1,6 @@ +export { emitForest, emitForestLines, parseFunctionRanges, parseOffsets } from "./ascii"; +export { cloneFunctionCov, cloneProcessCov, cloneScriptCov, cloneRangeCov } from "./clone"; +export { compareScriptCovs, compareFunctionCovs, compareRangeCovs } from "./compare"; +export { mergeFunctionCovs, mergeProcessCovs, mergeScriptCovs } from "./merge"; +export { RangeTree } from "./range-tree"; +export { ProcessCov, ScriptCov, FunctionCov, RangeCov } from "./types"; diff --git a/node_modules/@bcoe/v8-coverage/src/lib/merge.ts b/node_modules/@bcoe/v8-coverage/src/lib/merge.ts new file mode 100644 index 0000000..64d1918 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/src/lib/merge.ts @@ -0,0 +1,343 @@ +import { + deepNormalizeScriptCov, + normalizeFunctionCov, + normalizeProcessCov, + normalizeRangeTree, + normalizeScriptCov, +} from "./normalize"; +import { RangeTree } from "./range-tree"; +import { FunctionCov, ProcessCov, Range, RangeCov, ScriptCov } from "./types"; + +/** + * Merges a list of process coverages. + * + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param processCovs Process coverages to merge. + * @return Merged process coverage. + */ +export function mergeProcessCovs(processCovs: ReadonlyArray): ProcessCov { + if (processCovs.length === 0) { + return {result: []}; + } + + const urlToScripts: Map = new Map(); + for (const processCov of processCovs) { + for (const scriptCov of processCov.result) { + let scriptCovs: ScriptCov[] | undefined = urlToScripts.get(scriptCov.url); + if (scriptCovs === undefined) { + scriptCovs = []; + urlToScripts.set(scriptCov.url, scriptCovs); + } + scriptCovs.push(scriptCov); + } + } + + const result: ScriptCov[] = []; + for (const scripts of urlToScripts.values()) { + // assert: `scripts.length > 0` + result.push(mergeScriptCovs(scripts)!); + } + const merged: ProcessCov = {result}; + + normalizeProcessCov(merged); + return merged; +} + +/** + * Merges a list of matching script coverages. + * + * Scripts are matching if they have the same `url`. + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param scriptCovs Process coverages to merge. + * @return Merged script coverage, or `undefined` if the input list was empty. + */ +export function mergeScriptCovs(scriptCovs: ReadonlyArray): ScriptCov | undefined { + if (scriptCovs.length === 0) { + return undefined; + } else if (scriptCovs.length === 1) { + const merged: ScriptCov = scriptCovs[0]; + deepNormalizeScriptCov(merged); + return merged; + } + + const first: ScriptCov = scriptCovs[0]; + const scriptId: string = first.scriptId; + const url: string = first.url; + + const rangeToFuncs: Map = new Map(); + for (const scriptCov of scriptCovs) { + for (const funcCov of scriptCov.functions) { + const rootRange: string = stringifyFunctionRootRange(funcCov); + let funcCovs: FunctionCov[] | undefined = rangeToFuncs.get(rootRange); + + if (funcCovs === undefined || + // if the entry in rangeToFuncs is function-level granularity and + // the new coverage is block-level, prefer block-level. + (!funcCovs[0].isBlockCoverage && funcCov.isBlockCoverage)) { + funcCovs = []; + rangeToFuncs.set(rootRange, funcCovs); + } else if (funcCovs[0].isBlockCoverage && !funcCov.isBlockCoverage) { + // if the entry in rangeToFuncs is block-level granularity, we should + // not append function level granularity. + continue; + } + funcCovs.push(funcCov); + } + } + + const functions: FunctionCov[] = []; + for (const funcCovs of rangeToFuncs.values()) { + // assert: `funcCovs.length > 0` + functions.push(mergeFunctionCovs(funcCovs)!); + } + + const merged: ScriptCov = {scriptId, url, functions}; + normalizeScriptCov(merged); + return merged; +} + +/** + * Returns a string representation of the root range of the function. + * + * This string can be used to match function with same root range. + * The string is derived from the start and end offsets of the root range of + * the function. + * This assumes that `ranges` is non-empty (true for valid function coverages). + * + * @param funcCov Function coverage with the range to stringify + * @internal + */ +function stringifyFunctionRootRange(funcCov: Readonly): string { + const rootRange: RangeCov = funcCov.ranges[0]; + return `${rootRange.startOffset.toString(10)};${rootRange.endOffset.toString(10)}`; +} + +/** + * Merges a list of matching function coverages. + * + * Functions are matching if their root ranges have the same span. + * The result is normalized. + * The input values may be mutated, it is not safe to use them after passing + * them to this function. + * The computation is synchronous. + * + * @param funcCovs Function coverages to merge. + * @return Merged function coverage, or `undefined` if the input list was empty. + */ +export function mergeFunctionCovs(funcCovs: ReadonlyArray): FunctionCov | undefined { + if (funcCovs.length === 0) { + return undefined; + } else if (funcCovs.length === 1) { + const merged: FunctionCov = funcCovs[0]; + normalizeFunctionCov(merged); + return merged; + } + + const functionName: string = funcCovs[0].functionName; + + const trees: RangeTree[] = []; + for (const funcCov of funcCovs) { + // assert: `fn.ranges.length > 0` + // assert: `fn.ranges` is sorted + trees.push(RangeTree.fromSortedRanges(funcCov.ranges)!); + } + + // assert: `trees.length > 0` + const mergedTree: RangeTree = mergeRangeTrees(trees)!; + normalizeRangeTree(mergedTree); + const ranges: RangeCov[] = mergedTree.toRanges(); + const isBlockCoverage: boolean = !(ranges.length === 1 && ranges[0].count === 0); + + const merged: FunctionCov = {functionName, ranges, isBlockCoverage}; + // assert: `merged` is normalized + return merged; +} + +/** + * @precondition Same `start` and `end` for all the trees + */ +function mergeRangeTrees(trees: ReadonlyArray): RangeTree | undefined { + if (trees.length <= 1) { + return trees[0]; + } + const first: RangeTree = trees[0]; + let delta: number = 0; + for (const tree of trees) { + delta += tree.delta; + } + const children: RangeTree[] = mergeRangeTreeChildren(trees); + return new RangeTree(first.start, first.end, delta, children); +} + +class RangeTreeWithParent { + readonly parentIndex: number; + readonly tree: RangeTree; + + constructor(parentIndex: number, tree: RangeTree) { + this.parentIndex = parentIndex; + this.tree = tree; + } +} + +class StartEvent { + readonly offset: number; + readonly trees: RangeTreeWithParent[]; + + constructor(offset: number, trees: RangeTreeWithParent[]) { + this.offset = offset; + this.trees = trees; + } + + static compare(a: StartEvent, b: StartEvent): number { + return a.offset - b.offset; + } +} + +class StartEventQueue { + private readonly queue: StartEvent[]; + private nextIndex: number; + private pendingOffset: number; + private pendingTrees: RangeTreeWithParent[] | undefined; + + private constructor(queue: StartEvent[]) { + this.queue = queue; + this.nextIndex = 0; + this.pendingOffset = 0; + this.pendingTrees = undefined; + } + + static fromParentTrees(parentTrees: ReadonlyArray): StartEventQueue { + const startToTrees: Map = new Map(); + for (const [parentIndex, parentTree] of parentTrees.entries()) { + for (const child of parentTree.children) { + let trees: RangeTreeWithParent[] | undefined = startToTrees.get(child.start); + if (trees === undefined) { + trees = []; + startToTrees.set(child.start, trees); + } + trees.push(new RangeTreeWithParent(parentIndex, child)); + } + } + const queue: StartEvent[] = []; + for (const [startOffset, trees] of startToTrees) { + queue.push(new StartEvent(startOffset, trees)); + } + queue.sort(StartEvent.compare); + return new StartEventQueue(queue); + } + + setPendingOffset(offset: number): void { + this.pendingOffset = offset; + } + + pushPendingTree(tree: RangeTreeWithParent): void { + if (this.pendingTrees === undefined) { + this.pendingTrees = []; + } + this.pendingTrees.push(tree); + } + + next(): StartEvent | undefined { + const pendingTrees: RangeTreeWithParent[] | undefined = this.pendingTrees; + const nextEvent: StartEvent | undefined = this.queue[this.nextIndex]; + if (pendingTrees === undefined) { + this.nextIndex++; + return nextEvent; + } else if (nextEvent === undefined) { + this.pendingTrees = undefined; + return new StartEvent(this.pendingOffset, pendingTrees); + } else { + if (this.pendingOffset < nextEvent.offset) { + this.pendingTrees = undefined; + return new StartEvent(this.pendingOffset, pendingTrees); + } else { + if (this.pendingOffset === nextEvent.offset) { + this.pendingTrees = undefined; + for (const tree of pendingTrees) { + nextEvent.trees.push(tree); + } + } + this.nextIndex++; + return nextEvent; + } + } + } +} + +function mergeRangeTreeChildren(parentTrees: ReadonlyArray): RangeTree[] { + const result: RangeTree[] = []; + const startEventQueue: StartEventQueue = StartEventQueue.fromParentTrees(parentTrees); + const parentToNested: Map = new Map(); + let openRange: Range | undefined; + + while (true) { + const event: StartEvent | undefined = startEventQueue.next(); + if (event === undefined) { + break; + } + + if (openRange !== undefined && openRange.end <= event.offset) { + result.push(nextChild(openRange, parentToNested)); + openRange = undefined; + } + + if (openRange === undefined) { + let openRangeEnd: number = event.offset + 1; + for (const {parentIndex, tree} of event.trees) { + openRangeEnd = Math.max(openRangeEnd, tree.end); + insertChild(parentToNested, parentIndex, tree); + } + startEventQueue.setPendingOffset(openRangeEnd); + openRange = {start: event.offset, end: openRangeEnd}; + } else { + for (const {parentIndex, tree} of event.trees) { + if (tree.end > openRange.end) { + const right: RangeTree = tree.split(openRange.end); + startEventQueue.pushPendingTree(new RangeTreeWithParent(parentIndex, right)); + } + insertChild(parentToNested, parentIndex, tree); + } + } + } + if (openRange !== undefined) { + result.push(nextChild(openRange, parentToNested)); + } + + return result; +} + +function insertChild(parentToNested: Map, parentIndex: number, tree: RangeTree): void { + let nested: RangeTree[] | undefined = parentToNested.get(parentIndex); + if (nested === undefined) { + nested = []; + parentToNested.set(parentIndex, nested); + } + nested.push(tree); +} + +function nextChild(openRange: Range, parentToNested: Map): RangeTree { + const matchingTrees: RangeTree[] = []; + + for (const nested of parentToNested.values()) { + if (nested.length === 1 && nested[0].start === openRange.start && nested[0].end === openRange.end) { + matchingTrees.push(nested[0]); + } else { + matchingTrees.push(new RangeTree( + openRange.start, + openRange.end, + 0, + nested, + )); + } + } + parentToNested.clear(); + return mergeRangeTrees(matchingTrees)!; +} diff --git a/node_modules/@bcoe/v8-coverage/src/lib/normalize.ts b/node_modules/@bcoe/v8-coverage/src/lib/normalize.ts new file mode 100644 index 0000000..0269116 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/src/lib/normalize.ts @@ -0,0 +1,84 @@ +import { compareFunctionCovs, compareRangeCovs, compareScriptCovs } from "./compare"; +import { RangeTree } from "./range-tree"; +import { FunctionCov, ProcessCov, ScriptCov } from "./types"; + +/** + * Normalizes a process coverage. + * + * Sorts the scripts alphabetically by `url`. + * Reassigns script ids: the script at index `0` receives `"0"`, the script at + * index `1` receives `"1"` etc. + * This does not normalize the script coverages. + * + * @param processCov Process coverage to normalize. + */ +export function normalizeProcessCov(processCov: ProcessCov): void { + processCov.result.sort(compareScriptCovs); + for (const [scriptId, scriptCov] of processCov.result.entries()) { + scriptCov.scriptId = scriptId.toString(10); + } +} + +/** + * Normalizes a process coverage deeply. + * + * Normalizes the script coverages deeply, then normalizes the process coverage + * itself. + * + * @param processCov Process coverage to normalize. + */ +export function deepNormalizeProcessCov(processCov: ProcessCov): void { + for (const scriptCov of processCov.result) { + deepNormalizeScriptCov(scriptCov); + } + normalizeProcessCov(processCov); +} + +/** + * Normalizes a script coverage. + * + * Sorts the function by root range (pre-order sort). + * This does not normalize the function coverages. + * + * @param scriptCov Script coverage to normalize. + */ +export function normalizeScriptCov(scriptCov: ScriptCov): void { + scriptCov.functions.sort(compareFunctionCovs); +} + +/** + * Normalizes a script coverage deeply. + * + * Normalizes the function coverages deeply, then normalizes the script coverage + * itself. + * + * @param scriptCov Script coverage to normalize. + */ +export function deepNormalizeScriptCov(scriptCov: ScriptCov): void { + for (const funcCov of scriptCov.functions) { + normalizeFunctionCov(funcCov); + } + normalizeScriptCov(scriptCov); +} + +/** + * Normalizes a function coverage. + * + * Sorts the ranges (pre-order sort). + * TODO: Tree-based normalization of the ranges. + * + * @param funcCov Function coverage to normalize. + */ +export function normalizeFunctionCov(funcCov: FunctionCov): void { + funcCov.ranges.sort(compareRangeCovs); + const tree: RangeTree = RangeTree.fromSortedRanges(funcCov.ranges)!; + normalizeRangeTree(tree); + funcCov.ranges = tree.toRanges(); +} + +/** + * @internal + */ +export function normalizeRangeTree(tree: RangeTree): void { + tree.normalize(); +} diff --git a/node_modules/@bcoe/v8-coverage/src/lib/range-tree.ts b/node_modules/@bcoe/v8-coverage/src/lib/range-tree.ts new file mode 100644 index 0000000..941ec82 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/src/lib/range-tree.ts @@ -0,0 +1,156 @@ +import { RangeCov } from "./types"; + +export class RangeTree { + start: number; + end: number; + delta: number; + children: RangeTree[]; + + constructor( + start: number, + end: number, + delta: number, + children: RangeTree[], + ) { + this.start = start; + this.end = end; + this.delta = delta; + this.children = children; + } + + /** + * @precodition `ranges` are well-formed and pre-order sorted + */ + static fromSortedRanges(ranges: ReadonlyArray): RangeTree | undefined { + let root: RangeTree | undefined; + // Stack of parent trees and parent counts. + const stack: [RangeTree, number][] = []; + for (const range of ranges) { + const node: RangeTree = new RangeTree(range.startOffset, range.endOffset, range.count, []); + if (root === undefined) { + root = node; + stack.push([node, range.count]); + continue; + } + let parent: RangeTree; + let parentCount: number; + while (true) { + [parent, parentCount] = stack[stack.length - 1]; + // assert: `top !== undefined` (the ranges are sorted) + if (range.startOffset < parent.end) { + break; + } else { + stack.pop(); + } + } + node.delta -= parentCount; + parent.children.push(node); + stack.push([node, range.count]); + } + return root; + } + + normalize(): void { + const children: RangeTree[] = []; + let curEnd: number; + let head: RangeTree | undefined; + const tail: RangeTree[] = []; + for (const child of this.children) { + if (head === undefined) { + head = child; + } else if (child.delta === head.delta && child.start === curEnd!) { + tail.push(child); + } else { + endChain(); + head = child; + } + curEnd = child.end; + } + if (head !== undefined) { + endChain(); + } + + if (children.length === 1) { + const child: RangeTree = children[0]; + if (child.start === this.start && child.end === this.end) { + this.delta += child.delta; + this.children = child.children; + // `.lazyCount` is zero for both (both are after normalization) + return; + } + } + + this.children = children; + + function endChain(): void { + if (tail.length !== 0) { + head!.end = tail[tail.length - 1].end; + for (const tailTree of tail) { + for (const subChild of tailTree.children) { + subChild.delta += tailTree.delta - head!.delta; + head!.children.push(subChild); + } + } + tail.length = 0; + } + head!.normalize(); + children.push(head!); + } + } + + /** + * @precondition `tree.start < value && value < tree.end` + * @return RangeTree Right part + */ + split(value: number): RangeTree { + let leftChildLen: number = this.children.length; + let mid: RangeTree | undefined; + + // TODO(perf): Binary search (check overhead) + for (let i: number = 0; i < this.children.length; i++) { + const child: RangeTree = this.children[i]; + if (child.start < value && value < child.end) { + mid = child.split(value); + leftChildLen = i + 1; + break; + } else if (child.start >= value) { + leftChildLen = i; + break; + } + } + + const rightLen: number = this.children.length - leftChildLen; + const rightChildren: RangeTree[] = this.children.splice(leftChildLen, rightLen); + if (mid !== undefined) { + rightChildren.unshift(mid); + } + const result: RangeTree = new RangeTree( + value, + this.end, + this.delta, + rightChildren, + ); + this.end = value; + return result; + } + + /** + * Get the range coverages corresponding to the tree. + * + * The ranges are pre-order sorted. + */ + toRanges(): RangeCov[] { + const ranges: RangeCov[] = []; + // Stack of parent trees and counts. + const stack: [RangeTree, number][] = [[this, 0]]; + while (stack.length > 0) { + const [cur, parentCount]: [RangeTree, number] = stack.pop()!; + const count: number = parentCount + cur.delta; + ranges.push({startOffset: cur.start, endOffset: cur.end, count}); + for (let i: number = cur.children.length - 1; i >= 0; i--) { + stack.push([cur.children[i], count]); + } + } + return ranges; + } +} diff --git a/node_modules/@bcoe/v8-coverage/src/lib/types.ts b/node_modules/@bcoe/v8-coverage/src/lib/types.ts new file mode 100644 index 0000000..cc2cfc5 --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/src/lib/types.ts @@ -0,0 +1,26 @@ +export interface ProcessCov { + result: ScriptCov[]; +} + +export interface ScriptCov { + scriptId: string; + url: string; + functions: FunctionCov[]; +} + +export interface FunctionCov { + functionName: string; + ranges: RangeCov[]; + isBlockCoverage: boolean; +} + +export interface Range { + readonly start: number; + readonly end: number; +} + +export interface RangeCov { + startOffset: number; + endOffset: number; + count: number; +} diff --git a/node_modules/@bcoe/v8-coverage/src/test/merge.spec.ts b/node_modules/@bcoe/v8-coverage/src/test/merge.spec.ts new file mode 100644 index 0000000..9d5522a --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/src/test/merge.spec.ts @@ -0,0 +1,280 @@ +import chai from "chai"; +import fs from "fs"; +import path from "path"; +import { FunctionCov, mergeFunctionCovs, mergeProcessCovs, mergeScriptCovs, ProcessCov, ScriptCov } from "../lib"; + +const REPO_ROOT: string = path.join(__dirname, "..", "..", "..", ".."); +const BENCHES_INPUT_DIR: string = path.join(REPO_ROOT, "benches"); +const BENCHES_DIR: string = path.join(REPO_ROOT, "test-data", "merge", "benches"); +const RANGES_DIR: string = path.join(REPO_ROOT, "test-data", "merge", "ranges"); +const BENCHES_TIMEOUT: number = 20000; // 20sec + +interface MergeRangeItem { + name: string; + status: "run" | "skip" | "only"; + inputs: ProcessCov[]; + expected: ProcessCov; +} + +const FIXTURES_DIR: string = path.join(REPO_ROOT, "test-data", "bugs"); +function loadFixture(name: string) { + const content: string = fs.readFileSync( + path.resolve(FIXTURES_DIR, `${name}.json`), + {encoding: "UTF-8"}, + ); + return JSON.parse(content); +} + +describe("merge", () => { + describe("Various", () => { + it("accepts empty arrays for `mergeProcessCovs`", () => { + const inputs: ProcessCov[] = []; + const expected: ProcessCov = {result: []}; + const actual: ProcessCov = mergeProcessCovs(inputs); + chai.assert.deepEqual(actual, expected); + }); + + it("accepts empty arrays for `mergeScriptCovs`", () => { + const inputs: ScriptCov[] = []; + const expected: ScriptCov | undefined = undefined; + const actual: ScriptCov | undefined = mergeScriptCovs(inputs); + chai.assert.deepEqual(actual, expected); + }); + + it("accepts empty arrays for `mergeFunctionCovs`", () => { + const inputs: FunctionCov[] = []; + const expected: FunctionCov | undefined = undefined; + const actual: FunctionCov | undefined = mergeFunctionCovs(inputs); + chai.assert.deepEqual(actual, expected); + }); + + it("accepts arrays with a single item for `mergeProcessCovs`", () => { + const inputs: ProcessCov[] = [ + { + result: [ + { + scriptId: "123", + url: "/lib.js", + functions: [ + { + functionName: "test", + isBlockCoverage: true, + ranges: [ + {startOffset: 0, endOffset: 4, count: 2}, + {startOffset: 1, endOffset: 2, count: 1}, + {startOffset: 2, endOffset: 3, count: 1}, + ], + }, + ], + }, + ], + }, + ]; + const expected: ProcessCov = { + result: [ + { + scriptId: "0", + url: "/lib.js", + functions: [ + { + functionName: "test", + isBlockCoverage: true, + ranges: [ + {startOffset: 0, endOffset: 4, count: 2}, + {startOffset: 1, endOffset: 3, count: 1}, + ], + }, + ], + }, + ], + }; + const actual: ProcessCov = mergeProcessCovs(inputs); + chai.assert.deepEqual(actual, expected); + }); + + describe("mergeProcessCovs", () => { + // see: https://github.com/demurgos/v8-coverage/issues/2 + it("handles function coverage merged into block coverage", () => { + const blockCoverage: ProcessCov = loadFixture("issue-2-block-coverage"); + const functionCoverage: ProcessCov = loadFixture("issue-2-func-coverage"); + const inputs: ProcessCov[] = [ + functionCoverage, + blockCoverage, + ]; + const expected: ProcessCov = loadFixture("issue-2-expected"); + const actual: ProcessCov = mergeProcessCovs(inputs); + chai.assert.deepEqual(actual, expected); + }); + + // see: https://github.com/demurgos/v8-coverage/issues/2 + it("handles block coverage merged into function coverage", () => { + const blockCoverage: ProcessCov = loadFixture("issue-2-block-coverage"); + const functionCoverage: ProcessCov = loadFixture("issue-2-func-coverage"); + const inputs: ProcessCov[] = [ + blockCoverage, + functionCoverage, + ]; + const expected: ProcessCov = loadFixture("issue-2-expected"); + const actual: ProcessCov = mergeProcessCovs(inputs); + chai.assert.deepEqual(actual, expected); + }); + }); + + it("accepts arrays with a single item for `mergeScriptCovs`", () => { + const inputs: ScriptCov[] = [ + { + scriptId: "123", + url: "/lib.js", + functions: [ + { + functionName: "test", + isBlockCoverage: true, + ranges: [ + {startOffset: 0, endOffset: 4, count: 2}, + {startOffset: 1, endOffset: 2, count: 1}, + {startOffset: 2, endOffset: 3, count: 1}, + ], + }, + ], + }, + ]; + const expected: ScriptCov | undefined = { + scriptId: "123", + url: "/lib.js", + functions: [ + { + functionName: "test", + isBlockCoverage: true, + ranges: [ + {startOffset: 0, endOffset: 4, count: 2}, + {startOffset: 1, endOffset: 3, count: 1}, + ], + }, + ], + }; + const actual: ScriptCov | undefined = mergeScriptCovs(inputs); + chai.assert.deepEqual(actual, expected); + }); + + it("accepts arrays with a single item for `mergeFunctionCovs`", () => { + const inputs: FunctionCov[] = [ + { + functionName: "test", + isBlockCoverage: true, + ranges: [ + {startOffset: 0, endOffset: 4, count: 2}, + {startOffset: 1, endOffset: 2, count: 1}, + {startOffset: 2, endOffset: 3, count: 1}, + ], + }, + ]; + const expected: FunctionCov = { + functionName: "test", + isBlockCoverage: true, + ranges: [ + {startOffset: 0, endOffset: 4, count: 2}, + {startOffset: 1, endOffset: 3, count: 1}, + ], + }; + const actual: FunctionCov | undefined = mergeFunctionCovs(inputs); + chai.assert.deepEqual(actual, expected); + }); + }); + + describe("ranges", () => { + for (const sourceFile of getSourceFiles()) { + const relPath: string = path.relative(RANGES_DIR, sourceFile); + describe(relPath, () => { + const content: string = fs.readFileSync(sourceFile, {encoding: "UTF-8"}); + const items: MergeRangeItem[] = JSON.parse(content); + for (const item of items) { + const test: () => void = () => { + const actual: ProcessCov | undefined = mergeProcessCovs(item.inputs); + chai.assert.deepEqual(actual, item.expected); + }; + switch (item.status) { + case "run": + it(item.name, test); + break; + case "only": + it.only(item.name, test); + break; + case "skip": + it.skip(item.name, test); + break; + default: + throw new Error(`Unexpected status: ${item.status}`); + } + } + }); + } + }); + + describe("benches", () => { + for (const bench of getBenches()) { + const BENCHES_TO_SKIP: Set = new Set(); + if (process.env.CI === "true") { + // Skip very large benchmarks when running continuous integration + BENCHES_TO_SKIP.add("node@10.11.0"); + BENCHES_TO_SKIP.add("npm@6.4.1"); + } + + const name: string = path.basename(bench); + + if (BENCHES_TO_SKIP.has(name)) { + it.skip(`${name} (skipped: too large for CI)`, testBench); + } else { + it(name, testBench); + } + + async function testBench(this: Mocha.Context) { + this.timeout(BENCHES_TIMEOUT); + + const inputFileNames: string[] = await fs.promises.readdir(bench); + const inputPromises: Promise[] = []; + for (const inputFileName of inputFileNames) { + const resolved: string = path.join(bench, inputFileName); + inputPromises.push(fs.promises.readFile(resolved).then(buffer => JSON.parse(buffer.toString("UTF-8")))); + } + const inputs: ProcessCov[] = await Promise.all(inputPromises); + const expectedPath: string = path.join(BENCHES_DIR, `${name}.json`); + const expectedContent: string = await fs.promises.readFile(expectedPath, {encoding: "UTF-8"}) as string; + const expected: ProcessCov = JSON.parse(expectedContent); + const startTime: number = Date.now(); + const actual: ProcessCov | undefined = mergeProcessCovs(inputs); + const endTime: number = Date.now(); + console.error(`Time (${name}): ${(endTime - startTime) / 1000}`); + chai.assert.deepEqual(actual, expected); + console.error(`OK: ${name}`); + } + } + }); +}); + +function getSourceFiles() { + return getSourcesFrom(RANGES_DIR); + + function* getSourcesFrom(dir: string): Iterable { + const names: string[] = fs.readdirSync(dir); + for (const name of names) { + const resolved: string = path.join(dir, name); + const stat: fs.Stats = fs.statSync(resolved); + if (stat.isDirectory()) { + yield* getSourcesFrom(dir); + } else { + yield resolved; + } + } + } +} + +function* getBenches(): Iterable { + const names: string[] = fs.readdirSync(BENCHES_INPUT_DIR); + for (const name of names) { + const resolved: string = path.join(BENCHES_INPUT_DIR, name); + const stat: fs.Stats = fs.statSync(resolved); + if (stat.isDirectory()) { + yield resolved; + } + } +} diff --git a/node_modules/@bcoe/v8-coverage/tsconfig.json b/node_modules/@bcoe/v8-coverage/tsconfig.json new file mode 100644 index 0000000..73db48f --- /dev/null +++ b/node_modules/@bcoe/v8-coverage/tsconfig.json @@ -0,0 +1,59 @@ +{ + "compilerOptions": { + "allowJs": false, + "allowSyntheticDefaultImports": true, + "allowUnreachableCode": false, + "allowUnusedLabels": false, + "alwaysStrict": true, + "charset": "utf8", + "checkJs": false, + "declaration": false, + "disableSizeLimit": false, + "downlevelIteration": false, + "emitBOM": false, + "emitDecoratorMetadata": true, + "esModuleInterop": true, + "experimentalDecorators": true, + "forceConsistentCasingInFileNames": true, + "importHelpers": false, + "inlineSourceMap": false, + "inlineSources": false, + "isolatedModules": false, + "lib": [ + "es2017", + "esnext.asynciterable" + ], + "locale": "en-us", + "module": "commonjs", + "moduleResolution": "node", + "newLine": "lf", + "noEmit": false, + "noEmitHelpers": false, + "noEmitOnError": true, + "noErrorTruncation": true, + "noFallthroughCasesInSwitch": true, + "noImplicitAny": true, + "noImplicitReturns": true, + "noImplicitThis": true, + "noStrictGenericChecks": false, + "noUnusedLocals": true, + "noUnusedParameters": false, + "noImplicitUseStrict": false, + "noLib": false, + "noResolve": false, + "preserveConstEnums": false, + "removeComments": false, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "strictNullChecks": true, + "suppressExcessPropertyErrors": false, + "suppressImplicitAnyIndexErrors": false, + "target": "es2017", + "traceResolution": false, + "typeRoots": [ + "src/lib/custom-typings", + "node_modules/@types" + ] + } +} diff --git a/node_modules/@istanbuljs/load-nyc-config/CHANGELOG.md b/node_modules/@istanbuljs/load-nyc-config/CHANGELOG.md new file mode 100644 index 0000000..980719e --- /dev/null +++ b/node_modules/@istanbuljs/load-nyc-config/CHANGELOG.md @@ -0,0 +1,41 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [1.1.0](https://github.com/istanbuljs/load-nyc-config/compare/v1.0.0...v1.1.0) (2020-05-20) + + +### Features + +* Create `isLoading` function ([#15](https://github.com/istanbuljs/load-nyc-config/issues/15)) ([0e58b51](https://github.com/istanbuljs/load-nyc-config/commit/0e58b516f663af7ed710ba27f2090fc28bc3fdb1)) +* Support loading ES module config from `.js` files ([#14](https://github.com/istanbuljs/load-nyc-config/issues/14)) ([b1ea369](https://github.com/istanbuljs/load-nyc-config/commit/b1ea369f1e5162133b7057c5e3fefb8085671ab3)) + +## [1.0.0](https://github.com/istanbuljs/load-nyc-config/compare/v1.0.0-alpha.2...v1.0.0) (2019-12-20) + + +### Features + +* Version bump only ([#11](https://github.com/istanbuljs/load-nyc-config/issues/11)) ([8c3f1be](https://github.com/istanbuljs/load-nyc-config/commit/8c3f1be8d4d30161088a79878c02210db4c2fbfb)) + +## [1.0.0-alpha.2](https://github.com/istanbuljs/load-nyc-config/compare/v1.0.0-alpha.1...v1.0.0-alpha.2) (2019-11-24) + + +### Bug Fixes + +* Remove support for loading .js config under `type: 'module'` ([#10](https://github.com/istanbuljs/load-nyc-config/issues/10)) ([420fe87](https://github.com/istanbuljs/load-nyc-config/commit/420fe87da7dde3e9d98ef07f0a8a03d2b4d1dcb1)) +* Resolve cwd per config that sets it ([#9](https://github.com/istanbuljs/load-nyc-config/issues/9)) ([649efdc](https://github.com/istanbuljs/load-nyc-config/commit/649efdcda405c476764eebcf15af5da542fb21e1)) + +## [1.0.0-alpha.1](https://github.com/istanbuljs/load-nyc-config/compare/v1.0.0-alpha.0...v1.0.0-alpha.1) (2019-10-08) + + +### Bug Fixes + +* Add `cwd` to returned config object ([#8](https://github.com/istanbuljs/load-nyc-config/issues/8)) ([cb5184a](https://github.com/istanbuljs/load-nyc-config/commit/cb5184a)) + +## 1.0.0-alpha.0 (2019-10-06) + + +### Features + +* Add support for loading config from ESM modules ([#7](https://github.com/istanbuljs/load-nyc-config/issues/7)) ([bc5ea3e](https://github.com/istanbuljs/load-nyc-config/commit/bc5ea3e)), closes [#6](https://github.com/istanbuljs/load-nyc-config/issues/6) +* Initial implementation ([ff90134](https://github.com/istanbuljs/load-nyc-config/commit/ff90134)) diff --git a/node_modules/@istanbuljs/load-nyc-config/LICENSE b/node_modules/@istanbuljs/load-nyc-config/LICENSE new file mode 100644 index 0000000..345e587 --- /dev/null +++ b/node_modules/@istanbuljs/load-nyc-config/LICENSE @@ -0,0 +1,16 @@ +ISC License + +Copyright (c) 2019, 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/@istanbuljs/load-nyc-config/README.md b/node_modules/@istanbuljs/load-nyc-config/README.md new file mode 100644 index 0000000..533db74 --- /dev/null +++ b/node_modules/@istanbuljs/load-nyc-config/README.md @@ -0,0 +1,64 @@ +# @istanbuljs/load-nyc-config + +The utility function which NYC uses to load configuration. +This can be used by outside programs to calculate the configuration. +Command-line arguments are not considered by this function. + +```js +const {loadNycConfig} = require('@istanbuljs/load-nyc-config'); + +(async () { + console.log(await loadNycConfig()); +})(); +``` + +## loadNycConfig([options]) + +### options.cwd + +Type: `string` +Default: `cwd` from parent nyc process or `process.cwd()` + +### options.nycrcPath + +Type: `string` +Default: `undefined` + +Name of the file containing nyc configuration. +This can be a relative or absolute path. +Relative paths can exist at `options.cwd` or any parent directory. +If an nycrc is specified but cannot be found an exception is thrown. + +If no nycrc option is provided the default priority of config files are: + +* .nycrc +* .nycrc.json +* .nycrc.yml +* .nycrc.yaml +* nyc.config.js +* nyc.config.cjs +* nyc.config.mjs + +## Configuration merging + +Configuration is first loaded from `package.json` if found, this serves as the package +defaults. These options can be overridden by an nycrc if found. Arrays are not merged, +so if `package.json` sets `"require": ["@babel/register"]` and `.nycrc` sets `"require": ["esm"]` +the effective require setting will only include `"esm"`. + +## isLoading + +```js +const {isLoading} = require('@istanbuljs/load-nyc-config'); + +console.log(isLoading()); +``` + +In some cases source transformation hooks can get installed before the configuration is +loaded. This allows hooks to ignore source loads that occur during configuration load. + +## `@istanbuljs/load-nyc-config` for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of `@istanbuljs/load-nyc-config` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-istanbuljs-load-nyc-config?utm_source=npm-istanbuljs-load-nyc-config&utm_medium=referral&utm_campaign=enterprise) diff --git a/node_modules/@istanbuljs/load-nyc-config/index.js b/node_modules/@istanbuljs/load-nyc-config/index.js new file mode 100644 index 0000000..0c8c05e --- /dev/null +++ b/node_modules/@istanbuljs/load-nyc-config/index.js @@ -0,0 +1,166 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const {promisify} = require('util'); +const camelcase = require('camelcase'); +const findUp = require('find-up'); +const resolveFrom = require('resolve-from'); +const getPackageType = require('get-package-type'); + +const readFile = promisify(fs.readFile); + +let loadActive = false; + +function isLoading() { + return loadActive; +} + +const standardConfigFiles = [ + '.nycrc', + '.nycrc.json', + '.nycrc.yml', + '.nycrc.yaml', + 'nyc.config.js', + 'nyc.config.cjs', + 'nyc.config.mjs' +]; + +function camelcasedConfig(config) { + const results = {}; + for (const [field, value] of Object.entries(config)) { + results[camelcase(field)] = value; + } + + return results; +} + +async function findPackage(options) { + const cwd = options.cwd || process.env.NYC_CWD || process.cwd(); + const pkgPath = await findUp('package.json', {cwd}); + if (pkgPath) { + const pkgConfig = JSON.parse(await readFile(pkgPath, 'utf8')).nyc || {}; + if ('cwd' in pkgConfig) { + pkgConfig.cwd = path.resolve(path.dirname(pkgPath), pkgConfig.cwd); + } + + return { + cwd: path.dirname(pkgPath), + pkgConfig + }; + } + + return { + cwd, + pkgConfig: {} + }; +} + +async function actualLoad(configFile) { + if (!configFile) { + return {}; + } + + const configExt = path.extname(configFile).toLowerCase(); + switch (configExt) { + case '.js': + /* istanbul ignore next: coverage for 13.2.0+ is shown in load-esm.js */ + if (await getPackageType(configFile) === 'module') { + return require('./load-esm')(configFile); + } + + /* fallthrough */ + case '.cjs': + return require(configFile); + /* istanbul ignore next: coverage for 13.2.0+ is shown in load-esm.js */ + case '.mjs': + return require('./load-esm')(configFile); + case '.yml': + case '.yaml': + return require('js-yaml').load(await readFile(configFile, 'utf8')); + default: + return JSON.parse(await readFile(configFile, 'utf8')); + } +} + +async function loadFile(configFile) { + /* This lets @istanbuljs/esm-loader-hook avoid circular initialization when loading + * configuration. This should generally only happen when the loader hook is active + * on the main nyc process. */ + loadActive = true; + + try { + return await actualLoad(configFile); + } finally { + loadActive = false; + } +} + +async function applyExtends(config, filename, loopCheck = new Set()) { + config = camelcasedConfig(config); + if ('extends' in config) { + const extConfigs = [].concat(config.extends); + if (extConfigs.some(e => typeof e !== 'string')) { + throw new TypeError(`${filename} contains an invalid 'extends' option`); + } + + delete config.extends; + const filePath = path.dirname(filename); + for (const extConfig of extConfigs) { + const configFile = resolveFrom.silent(filePath, extConfig) || + resolveFrom.silent(filePath, './' + extConfig); + if (!configFile) { + throw new Error(`Could not resolve configuration file ${extConfig} from ${path.dirname(filename)}.`); + } + + if (loopCheck.has(configFile)) { + throw new Error(`Circular extended configurations: '${configFile}'.`); + } + + loopCheck.add(configFile); + + // eslint-disable-next-line no-await-in-loop + const configLoaded = await loadFile(configFile); + if ('cwd' in configLoaded) { + configLoaded.cwd = path.resolve(path.dirname(configFile), configLoaded.cwd); + } + + Object.assign( + config, + // eslint-disable-next-line no-await-in-loop + await applyExtends(configLoaded, configFile, loopCheck) + ); + } + } + + return config; +} + +async function loadNycConfig(options = {}) { + const {cwd, pkgConfig} = await findPackage(options); + const configFiles = [].concat(options.nycrcPath || standardConfigFiles); + const configFile = await findUp(configFiles, {cwd}); + if (options.nycrcPath && !configFile) { + throw new Error(`Requested configuration file ${options.nycrcPath} not found`); + } + + const config = { + cwd, + ...(await applyExtends(pkgConfig, path.join(cwd, 'package.json'))), + ...(await applyExtends(await loadFile(configFile), configFile)) + }; + + const arrayFields = ['require', 'extension', 'exclude', 'include']; + for (const arrayField of arrayFields) { + if (config[arrayField]) { + config[arrayField] = [].concat(config[arrayField]); + } + } + + return config; +} + +module.exports = { + loadNycConfig, + isLoading +}; diff --git a/node_modules/@istanbuljs/load-nyc-config/load-esm.js b/node_modules/@istanbuljs/load-nyc-config/load-esm.js new file mode 100644 index 0000000..0eb517e --- /dev/null +++ b/node_modules/@istanbuljs/load-nyc-config/load-esm.js @@ -0,0 +1,12 @@ +'use strict'; + +const {pathToFileURL} = require('url'); + +module.exports = async filename => { + const mod = await import(pathToFileURL(filename)); + if ('default' in mod === false) { + throw new Error(`${filename} has no default export`); + } + + return mod.default; +}; diff --git a/node_modules/@istanbuljs/load-nyc-config/package.json b/node_modules/@istanbuljs/load-nyc-config/package.json new file mode 100644 index 0000000..53207ef --- /dev/null +++ b/node_modules/@istanbuljs/load-nyc-config/package.json @@ -0,0 +1,49 @@ +{ + "name": "@istanbuljs/load-nyc-config", + "version": "1.1.0", + "description": "Utility function to load nyc configuration", + "main": "index.js", + "scripts": { + "pretest": "xo", + "test": "tap", + "snap": "npm test -- --snapshot", + "release": "standard-version" + }, + "engines": { + "node": ">=8" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "git+https://github.com/istanbuljs/load-nyc-config.git" + }, + "bugs": { + "url": "https://github.com/istanbuljs/load-nyc-config/issues" + }, + "homepage": "https://github.com/istanbuljs/load-nyc-config#readme", + "dependencies": { + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" + }, + "devDependencies": { + "semver": "^6.3.0", + "standard-version": "^7.0.0", + "tap": "^14.10.5", + "xo": "^0.25.3" + }, + "xo": { + "ignores": [ + "test/fixtures/extends/invalid.*" + ], + "rules": { + "require-atomic-updates": 0, + "capitalized-comments": 0, + "unicorn/import-index": 0, + "import/extensions": 0, + "import/no-useless-path-segments": 0 + } + } +} diff --git a/node_modules/@istanbuljs/schema/CHANGELOG.md b/node_modules/@istanbuljs/schema/CHANGELOG.md new file mode 100644 index 0000000..afdc835 --- /dev/null +++ b/node_modules/@istanbuljs/schema/CHANGELOG.md @@ -0,0 +1,44 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [0.1.3](https://github.com/istanbuljs/schema/compare/v0.1.2...v0.1.3) (2021-02-13) + + +### Features + +* Add `classPrivateMethods` and `topLevelAwait` default support ([#17](https://github.com/istanbuljs/schema/issues/17)) ([e732889](https://github.com/istanbuljs/schema/commit/e7328894ddeb61da256c1f13c2c2cc2e04f181df)), closes [#16](https://github.com/istanbuljs/schema/issues/16) +* Add `numericSeparator` to default `parserPlugins` ([#12](https://github.com/istanbuljs/schema/issues/12)) ([fe32f00](https://github.com/istanbuljs/schema/commit/fe32f002f54c61467b1c1a487081f51c85ec8d10)), closes [#5](https://github.com/istanbuljs/schema/issues/5) +* Add babel.config.mjs to default exclude ([#10](https://github.com/istanbuljs/schema/issues/10)) ([a4dbeaa](https://github.com/istanbuljs/schema/commit/a4dbeaa7045490a4d46754801ac71f5d99c9bd79)) + + +### Bug Fixes + +* Exclude tests with `tsx` or `jsx` extensions ([#13](https://github.com/istanbuljs/schema/issues/13)) ([c7747f7](https://github.com/istanbuljs/schema/commit/c7747f7a7df8a2b770036834af77dfd0ee445733)), closes [#11](https://github.com/istanbuljs/schema/issues/11) + +### [0.1.2](https://github.com/istanbuljs/schema/compare/v0.1.1...v0.1.2) (2019-12-05) + + +### Features + +* Ignore *.d.ts ([#6](https://github.com/istanbuljs/schema/issues/6)) ([d867eaf](https://github.com/istanbuljs/schema/commit/d867eaff6ca4abcd4301990e2bdcdf53e438e9c4)) +* Update default exclude of dev tool configurations ([#7](https://github.com/istanbuljs/schema/issues/7)) ([c89f818](https://github.com/istanbuljs/schema/commit/c89f8185f30879bcdf8d2f1c3b7aba0ac7056fa9)) + +## [0.1.1](https://github.com/istanbuljs/schema/compare/v0.1.0...v0.1.1) (2019-10-07) + + +### Bug Fixes + +* Add missing `instrument` option ([#3](https://github.com/istanbuljs/schema/issues/3)) ([bf1217d](https://github.com/istanbuljs/schema/commit/bf1217d)) + + +### Features + +* Add `use-spawn-wrap` nyc option ([#4](https://github.com/istanbuljs/schema/issues/4)) ([b2ce2e8](https://github.com/istanbuljs/schema/commit/b2ce2e8)) + +## 0.1.0 (2019-10-05) + + +### Features + +* Initial implementation ([99bd3a5](https://github.com/istanbuljs/schema/commit/99bd3a5)) diff --git a/node_modules/@istanbuljs/schema/LICENSE b/node_modules/@istanbuljs/schema/LICENSE new file mode 100644 index 0000000..807a18b --- /dev/null +++ b/node_modules/@istanbuljs/schema/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 CFWare, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@istanbuljs/schema/README.md b/node_modules/@istanbuljs/schema/README.md new file mode 100644 index 0000000..9cac028 --- /dev/null +++ b/node_modules/@istanbuljs/schema/README.md @@ -0,0 +1,30 @@ +# @istanbuljs/schema + +[![Travis CI][travis-image]][travis-url] +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![MIT][license-image]](LICENSE) + +Schemas describing various structures used by nyc and istanbuljs + +## Usage + +```js +const {nyc} = require('@istanbuljs/schema').defaults; + +console.log(`Default exclude list:\n\t* ${nyc.exclude.join('\n\t* ')}`); +``` + +## `@istanbuljs/schema` for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of `@istanbuljs/schema` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-istanbuljs-schema?utm_source=npm-istanbuljs-schema&utm_medium=referral&utm_campaign=enterprise) + +[npm-image]: https://img.shields.io/npm/v/@istanbuljs/schema.svg +[npm-url]: https://npmjs.org/package/@istanbuljs/schema +[travis-image]: https://travis-ci.org/istanbuljs/schema.svg?branch=master +[travis-url]: https://travis-ci.org/istanbuljs/schema +[downloads-image]: https://img.shields.io/npm/dm/@istanbuljs/schema.svg +[downloads-url]: https://npmjs.org/package/@istanbuljs/schema +[license-image]: https://img.shields.io/npm/l/@istanbuljs/schema.svg diff --git a/node_modules/@istanbuljs/schema/default-exclude.js b/node_modules/@istanbuljs/schema/default-exclude.js new file mode 100644 index 0000000..c6bb526 --- /dev/null +++ b/node_modules/@istanbuljs/schema/default-exclude.js @@ -0,0 +1,22 @@ +'use strict'; + +const defaultExtension = require('./default-extension.js'); +const testFileExtensions = defaultExtension + .map(extension => extension.slice(1)) + .join(','); + +module.exports = [ + 'coverage/**', + 'packages/*/test{,s}/**', + '**/*.d.ts', + 'test{,s}/**', + `test{,-*}.{${testFileExtensions}}`, + `**/*{.,-}test.{${testFileExtensions}}`, + '**/__tests__/**', + + /* Exclude common development tool configuration files */ + '**/{ava,babel,nyc}.config.{js,cjs,mjs}', + '**/jest.config.{js,cjs,mjs,ts}', + '**/{karma,rollup,webpack}.config.js', + '**/.{eslint,mocha}rc.{js,cjs}' +]; diff --git a/node_modules/@istanbuljs/schema/default-extension.js b/node_modules/@istanbuljs/schema/default-extension.js new file mode 100644 index 0000000..46ebadc --- /dev/null +++ b/node_modules/@istanbuljs/schema/default-extension.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = [ + '.js', + '.cjs', + '.mjs', + '.ts', + '.tsx', + '.jsx' +]; diff --git a/node_modules/@istanbuljs/schema/index.js b/node_modules/@istanbuljs/schema/index.js new file mode 100644 index 0000000..b35f610 --- /dev/null +++ b/node_modules/@istanbuljs/schema/index.js @@ -0,0 +1,466 @@ +'use strict'; + +const defaultExclude = require('./default-exclude.js'); +const defaultExtension = require('./default-extension.js'); + +const nycCommands = { + all: [null, 'check-coverage', 'instrument', 'merge', 'report'], + testExclude: [null, 'instrument', 'report', 'check-coverage'], + instrument: [null, 'instrument'], + checkCoverage: [null, 'report', 'check-coverage'], + report: [null, 'report'], + main: [null], + instrumentOnly: ['instrument'] +}; + +const cwd = { + description: 'working directory used when resolving paths', + type: 'string', + get default() { + return process.cwd(); + }, + nycCommands: nycCommands.all +}; + +const nycrcPath = { + description: 'specify an explicit path to find nyc configuration', + nycCommands: nycCommands.all +}; + +const tempDir = { + description: 'directory to output raw coverage information to', + type: 'string', + default: './.nyc_output', + nycAlias: 't', + nycHiddenAlias: 'temp-directory', + nycCommands: [null, 'check-coverage', 'merge', 'report'] +}; + +const testExclude = { + exclude: { + description: 'a list of specific files and directories that should be excluded from coverage, glob patterns are supported', + type: 'array', + items: { + type: 'string' + }, + default: defaultExclude, + nycCommands: nycCommands.testExclude, + nycAlias: 'x' + }, + excludeNodeModules: { + description: 'whether or not to exclude all node_module folders (i.e. **/node_modules/**) by default', + type: 'boolean', + default: true, + nycCommands: nycCommands.testExclude + }, + include: { + description: 'a list of specific files that should be covered, glob patterns are supported', + type: 'array', + items: { + type: 'string' + }, + default: [], + nycCommands: nycCommands.testExclude, + nycAlias: 'n' + }, + extension: { + description: 'a list of extensions that nyc should handle in addition to .js', + type: 'array', + items: { + type: 'string' + }, + default: defaultExtension, + nycCommands: nycCommands.testExclude, + nycAlias: 'e' + } +}; + +const instrumentVisitor = { + coverageVariable: { + description: 'variable to store coverage', + type: 'string', + default: '__coverage__', + nycCommands: nycCommands.instrument + }, + coverageGlobalScope: { + description: 'scope to store the coverage variable', + type: 'string', + default: 'this', + nycCommands: nycCommands.instrument + }, + coverageGlobalScopeFunc: { + description: 'avoid potentially replaced `Function` when finding global scope', + type: 'boolean', + default: true, + nycCommands: nycCommands.instrument + }, + ignoreClassMethods: { + description: 'class method names to ignore for coverage', + type: 'array', + items: { + type: 'string' + }, + default: [], + nycCommands: nycCommands.instrument + } +}; + +const instrumentParseGen = { + autoWrap: { + description: 'allow `return` statements outside of functions', + type: 'boolean', + default: true, + nycCommands: nycCommands.instrument + }, + esModules: { + description: 'should files be treated as ES Modules', + type: 'boolean', + default: true, + nycCommands: nycCommands.instrument + }, + parserPlugins: { + description: 'babel parser plugins to use when parsing the source', + type: 'array', + items: { + type: 'string' + }, + /* Babel parser plugins are to be enabled when the feature is stage 3 and + * implemented in a released version of node.js. */ + default: [ + 'asyncGenerators', + 'bigInt', + 'classProperties', + 'classPrivateProperties', + 'classPrivateMethods', + 'dynamicImport', + 'importMeta', + 'numericSeparator', + 'objectRestSpread', + 'optionalCatchBinding', + 'topLevelAwait' + ], + nycCommands: nycCommands.instrument + }, + compact: { + description: 'should the output be compacted?', + type: 'boolean', + default: true, + nycCommands: nycCommands.instrument + }, + preserveComments: { + description: 'should comments be preserved in the output?', + type: 'boolean', + default: true, + nycCommands: nycCommands.instrument + }, + produceSourceMap: { + description: 'should source maps be produced?', + type: 'boolean', + default: true, + nycCommands: nycCommands.instrument + } +}; + +const checkCoverage = { + excludeAfterRemap: { + description: 'should exclude logic be performed after the source-map remaps filenames?', + type: 'boolean', + default: true, + nycCommands: nycCommands.checkCoverage + }, + branches: { + description: 'what % of branches must be covered?', + type: 'number', + default: 0, + minimum: 0, + maximum: 100, + nycCommands: nycCommands.checkCoverage + }, + functions: { + description: 'what % of functions must be covered?', + type: 'number', + default: 0, + minimum: 0, + maximum: 100, + nycCommands: nycCommands.checkCoverage + }, + lines: { + description: 'what % of lines must be covered?', + type: 'number', + default: 90, + minimum: 0, + maximum: 100, + nycCommands: nycCommands.checkCoverage + }, + statements: { + description: 'what % of statements must be covered?', + type: 'number', + default: 0, + minimum: 0, + maximum: 100, + nycCommands: nycCommands.checkCoverage + }, + perFile: { + description: 'check thresholds per file', + type: 'boolean', + default: false, + nycCommands: nycCommands.checkCoverage + } +}; + +const report = { + checkCoverage: { + description: 'check whether coverage is within thresholds provided', + type: 'boolean', + default: false, + nycCommands: nycCommands.report + }, + reporter: { + description: 'coverage reporter(s) to use', + type: 'array', + items: { + type: 'string' + }, + default: ['text'], + nycCommands: nycCommands.report, + nycAlias: 'r' + }, + reportDir: { + description: 'directory to output coverage reports in', + type: 'string', + default: 'coverage', + nycCommands: nycCommands.report + }, + showProcessTree: { + description: 'display the tree of spawned processes', + type: 'boolean', + default: false, + nycCommands: nycCommands.report + }, + skipEmpty: { + description: 'don\'t show empty files (no lines of code) in report', + type: 'boolean', + default: false, + nycCommands: nycCommands.report + }, + skipFull: { + description: 'don\'t show files with 100% statement, branch, and function coverage', + type: 'boolean', + default: false, + nycCommands: nycCommands.report + } +}; + +const nycMain = { + silent: { + description: 'don\'t output a report after tests finish running', + type: 'boolean', + default: false, + nycCommands: nycCommands.main, + nycAlias: 's' + }, + all: { + description: 'whether or not to instrument all files of the project (not just the ones touched by your test suite)', + type: 'boolean', + default: false, + nycCommands: nycCommands.main, + nycAlias: 'a' + }, + eager: { + description: 'instantiate the instrumenter at startup (see https://git.io/vMKZ9)', + type: 'boolean', + default: false, + nycCommands: nycCommands.main + }, + cache: { + description: 'cache instrumentation results for improved performance', + type: 'boolean', + default: true, + nycCommands: nycCommands.main, + nycAlias: 'c' + }, + cacheDir: { + description: 'explicitly set location for instrumentation cache', + type: 'string', + nycCommands: nycCommands.main + }, + babelCache: { + description: 'cache babel transpilation results for improved performance', + type: 'boolean', + default: false, + nycCommands: nycCommands.main + }, + useSpawnWrap: { + description: 'use spawn-wrap instead of setting process.env.NODE_OPTIONS', + type: 'boolean', + default: false, + nycCommands: nycCommands.main + }, + hookRequire: { + description: 'should nyc wrap require?', + type: 'boolean', + default: true, + nycCommands: nycCommands.main + }, + hookRunInContext: { + description: 'should nyc wrap vm.runInContext?', + type: 'boolean', + default: false, + nycCommands: nycCommands.main + }, + hookRunInThisContext: { + description: 'should nyc wrap vm.runInThisContext?', + type: 'boolean', + default: false, + nycCommands: nycCommands.main + }, + clean: { + description: 'should the .nyc_output folder be cleaned before executing tests', + type: 'boolean', + default: true, + nycCommands: nycCommands.main + } +}; + +const instrumentOnly = { + inPlace: { + description: 'should nyc run the instrumentation in place?', + type: 'boolean', + default: false, + nycCommands: nycCommands.instrumentOnly + }, + exitOnError: { + description: 'should nyc exit when an instrumentation failure occurs?', + type: 'boolean', + default: false, + nycCommands: nycCommands.instrumentOnly + }, + delete: { + description: 'should the output folder be deleted before instrumenting files?', + type: 'boolean', + default: false, + nycCommands: nycCommands.instrumentOnly + }, + completeCopy: { + description: 'should nyc copy all files from input to output as well as instrumented files?', + type: 'boolean', + default: false, + nycCommands: nycCommands.instrumentOnly + } +}; + +const nyc = { + description: 'nyc configuration options', + type: 'object', + properties: { + cwd, + nycrcPath, + tempDir, + + /* Test Exclude */ + ...testExclude, + + /* Instrumentation settings */ + ...instrumentVisitor, + + /* Instrumentation parser/generator settings */ + ...instrumentParseGen, + sourceMap: { + description: 'should nyc detect and handle source maps?', + type: 'boolean', + default: true, + nycCommands: nycCommands.instrument + }, + require: { + description: 'a list of additional modules that nyc should attempt to require in its subprocess, e.g., @babel/register, @babel/polyfill', + type: 'array', + items: { + type: 'string' + }, + default: [], + nycCommands: nycCommands.instrument, + nycAlias: 'i' + }, + instrument: { + description: 'should nyc handle instrumentation?', + type: 'boolean', + default: true, + nycCommands: nycCommands.instrument + }, + + /* Check coverage */ + ...checkCoverage, + + /* Report options */ + ...report, + + /* Main command options */ + ...nycMain, + + /* Instrument command options */ + ...instrumentOnly + } +}; + +const configs = { + nyc, + testExclude: { + description: 'test-exclude options', + type: 'object', + properties: { + cwd, + ...testExclude + } + }, + babelPluginIstanbul: { + description: 'babel-plugin-istanbul options', + type: 'object', + properties: { + cwd, + ...testExclude, + ...instrumentVisitor + } + }, + instrumentVisitor: { + description: 'instrument visitor options', + type: 'object', + properties: instrumentVisitor + }, + instrumenter: { + description: 'stand-alone instrumenter options', + type: 'object', + properties: { + ...instrumentVisitor, + ...instrumentParseGen + } + } +}; + +function defaultsReducer(defaults, [name, {default: value}]) { + /* Modifying arrays in defaults is safe, does not change schema. */ + if (Array.isArray(value)) { + value = [...value]; + } + + return Object.assign(defaults, {[name]: value}); +} + +module.exports = { + ...configs, + defaults: Object.keys(configs).reduce( + (defaults, id) => { + Object.defineProperty(defaults, id, { + enumerable: true, + get() { + /* This defers `process.cwd()` until defaults are requested. */ + return Object.entries(configs[id].properties) + .filter(([, info]) => 'default' in info) + .reduce(defaultsReducer, {}); + } + }); + + return defaults; + }, + {} + ) +}; diff --git a/node_modules/@istanbuljs/schema/package.json b/node_modules/@istanbuljs/schema/package.json new file mode 100644 index 0000000..1d22cde --- /dev/null +++ b/node_modules/@istanbuljs/schema/package.json @@ -0,0 +1,30 @@ +{ + "name": "@istanbuljs/schema", + "version": "0.1.3", + "description": "Schemas describing various structures used by nyc and istanbuljs", + "main": "index.js", + "scripts": { + "release": "standard-version --sign", + "pretest": "xo", + "test": "tap", + "snap": "npm test -- --snapshot" + }, + "engines": { + "node": ">=8" + }, + "author": "Corey Farrell", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/istanbuljs/schema.git" + }, + "bugs": { + "url": "https://github.com/istanbuljs/schema/issues" + }, + "homepage": "https://github.com/istanbuljs/schema#readme", + "devDependencies": { + "standard-version": "^7.0.0", + "tap": "^14.6.7", + "xo": "^0.25.3" + } +} diff --git a/node_modules/@jest/console/LICENSE b/node_modules/@jest/console/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/console/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/console/build/BufferedConsole.js b/node_modules/@jest/console/build/BufferedConsole.js new file mode 100644 index 0000000..2a14c51 --- /dev/null +++ b/node_modules/@jest/console/build/BufferedConsole.js @@ -0,0 +1,202 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _assert() { + const data = require('assert'); + _assert = function () { + return data; + }; + return data; +} +function _console() { + const data = require('console'); + _console = function () { + return data; + }; + return data; +} +function _util() { + const data = require('util'); + _util = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class BufferedConsole extends _console().Console { + _buffer = []; + _counters = {}; + _timers = {}; + _groupDepth = 0; + Console = _console().Console; + constructor() { + super({ + write: message => { + BufferedConsole.write(this._buffer, 'log', message, null); + return true; + } + }); + } + static write(buffer, type, message, level) { + const stackLevel = level != null ? level : 2; + const rawStack = new (_jestUtil().ErrorWithStack)( + undefined, + BufferedConsole.write + ).stack; + invariant(rawStack != null, 'always have a stack trace'); + const origin = rawStack + .split('\n') + .slice(stackLevel) + .filter(Boolean) + .join('\n'); + buffer.push({ + message, + origin, + type + }); + return buffer; + } + _log(type, message) { + BufferedConsole.write( + this._buffer, + type, + ' '.repeat(this._groupDepth) + message, + 3 + ); + } + assert(value, message) { + try { + (0, _assert().strict)(value, message); + } catch (error) { + if (!(error instanceof _assert().AssertionError)) { + throw error; + } + // https://github.com/facebook/jest/pull/13422#issuecomment-1273396392 + this._log('assert', error.toString().replace(/:\n\n.*\n/gs, '')); + } + } + count(label = 'default') { + if (!this._counters[label]) { + this._counters[label] = 0; + } + this._log( + 'count', + (0, _util().format)(`${label}: ${++this._counters[label]}`) + ); + } + countReset(label = 'default') { + this._counters[label] = 0; + } + debug(firstArg, ...rest) { + this._log('debug', (0, _util().format)(firstArg, ...rest)); + } + dir(firstArg, options = {}) { + const representation = (0, _util().inspect)(firstArg, options); + this._log('dir', (0, _util().formatWithOptions)(options, representation)); + } + dirxml(firstArg, ...rest) { + this._log('dirxml', (0, _util().format)(firstArg, ...rest)); + } + error(firstArg, ...rest) { + this._log('error', (0, _util().format)(firstArg, ...rest)); + } + group(title, ...rest) { + this._groupDepth++; + if (title != null || rest.length > 0) { + this._log( + 'group', + _chalk().default.bold((0, _util().format)(title, ...rest)) + ); + } + } + groupCollapsed(title, ...rest) { + this._groupDepth++; + if (title != null || rest.length > 0) { + this._log( + 'groupCollapsed', + _chalk().default.bold((0, _util().format)(title, ...rest)) + ); + } + } + groupEnd() { + if (this._groupDepth > 0) { + this._groupDepth--; + } + } + info(firstArg, ...rest) { + this._log('info', (0, _util().format)(firstArg, ...rest)); + } + log(firstArg, ...rest) { + this._log('log', (0, _util().format)(firstArg, ...rest)); + } + time(label = 'default') { + if (this._timers[label] != null) { + return; + } + this._timers[label] = new Date(); + } + timeEnd(label = 'default') { + const startTime = this._timers[label]; + if (startTime != null) { + const endTime = new Date(); + const time = endTime.getTime() - startTime.getTime(); + this._log( + 'time', + (0, _util().format)(`${label}: ${(0, _jestUtil().formatTime)(time)}`) + ); + delete this._timers[label]; + } + } + timeLog(label = 'default', ...data) { + const startTime = this._timers[label]; + if (startTime != null) { + const endTime = new Date(); + const time = endTime.getTime() - startTime.getTime(); + this._log( + 'time', + (0, _util().format)( + `${label}: ${(0, _jestUtil().formatTime)(time)}`, + ...data + ) + ); + } + } + warn(firstArg, ...rest) { + this._log('warn', (0, _util().format)(firstArg, ...rest)); + } + getBuffer() { + return this._buffer.length ? this._buffer : undefined; + } +} +exports.default = BufferedConsole; +function invariant(condition, message) { + if (!condition) { + throw new Error(message); + } +} diff --git a/node_modules/@jest/console/build/CustomConsole.js b/node_modules/@jest/console/build/CustomConsole.js new file mode 100644 index 0000000..a850be9 --- /dev/null +++ b/node_modules/@jest/console/build/CustomConsole.js @@ -0,0 +1,182 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _assert() { + const data = require('assert'); + _assert = function () { + return data; + }; + return data; +} +function _console() { + const data = require('console'); + _console = function () { + return data; + }; + return data; +} +function _util() { + const data = require('util'); + _util = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class CustomConsole extends _console().Console { + _stdout; + _stderr; + _formatBuffer; + _counters = {}; + _timers = {}; + _groupDepth = 0; + Console = _console().Console; + constructor(stdout, stderr, formatBuffer = (_type, message) => message) { + super(stdout, stderr); + this._stdout = stdout; + this._stderr = stderr; + this._formatBuffer = formatBuffer; + } + _log(type, message) { + (0, _jestUtil().clearLine)(this._stdout); + super.log( + this._formatBuffer(type, ' '.repeat(this._groupDepth) + message) + ); + } + _logError(type, message) { + (0, _jestUtil().clearLine)(this._stderr); + super.error( + this._formatBuffer(type, ' '.repeat(this._groupDepth) + message) + ); + } + assert(value, message) { + try { + (0, _assert().strict)(value, message); + } catch (error) { + if (!(error instanceof _assert().AssertionError)) { + throw error; + } + // https://github.com/facebook/jest/pull/13422#issuecomment-1273396392 + this._logError('assert', error.toString().replace(/:\n\n.*\n/gs, '')); + } + } + count(label = 'default') { + if (!this._counters[label]) { + this._counters[label] = 0; + } + this._log( + 'count', + (0, _util().format)(`${label}: ${++this._counters[label]}`) + ); + } + countReset(label = 'default') { + this._counters[label] = 0; + } + debug(firstArg, ...args) { + this._log('debug', (0, _util().format)(firstArg, ...args)); + } + dir(firstArg, options = {}) { + const representation = (0, _util().inspect)(firstArg, options); + this._log('dir', (0, _util().formatWithOptions)(options, representation)); + } + dirxml(firstArg, ...args) { + this._log('dirxml', (0, _util().format)(firstArg, ...args)); + } + error(firstArg, ...args) { + this._logError('error', (0, _util().format)(firstArg, ...args)); + } + group(title, ...args) { + this._groupDepth++; + if (title != null || args.length > 0) { + this._log( + 'group', + _chalk().default.bold((0, _util().format)(title, ...args)) + ); + } + } + groupCollapsed(title, ...args) { + this._groupDepth++; + if (title != null || args.length > 0) { + this._log( + 'groupCollapsed', + _chalk().default.bold((0, _util().format)(title, ...args)) + ); + } + } + groupEnd() { + if (this._groupDepth > 0) { + this._groupDepth--; + } + } + info(firstArg, ...args) { + this._log('info', (0, _util().format)(firstArg, ...args)); + } + log(firstArg, ...args) { + this._log('log', (0, _util().format)(firstArg, ...args)); + } + time(label = 'default') { + if (this._timers[label] != null) { + return; + } + this._timers[label] = new Date(); + } + timeEnd(label = 'default') { + const startTime = this._timers[label]; + if (startTime != null) { + const endTime = new Date().getTime(); + const time = endTime - startTime.getTime(); + this._log( + 'time', + (0, _util().format)(`${label}: ${(0, _jestUtil().formatTime)(time)}`) + ); + delete this._timers[label]; + } + } + timeLog(label = 'default', ...data) { + const startTime = this._timers[label]; + if (startTime != null) { + const endTime = new Date(); + const time = endTime.getTime() - startTime.getTime(); + this._log( + 'time', + (0, _util().format)( + `${label}: ${(0, _jestUtil().formatTime)(time)}`, + ...data + ) + ); + } + } + warn(firstArg, ...args) { + this._logError('warn', (0, _util().format)(firstArg, ...args)); + } + getBuffer() { + return undefined; + } +} +exports.default = CustomConsole; diff --git a/node_modules/@jest/console/build/NullConsole.js b/node_modules/@jest/console/build/NullConsole.js new file mode 100644 index 0000000..7703aae --- /dev/null +++ b/node_modules/@jest/console/build/NullConsole.js @@ -0,0 +1,35 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _CustomConsole = _interopRequireDefault(require('./CustomConsole')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/* eslint-disable @typescript-eslint/no-empty-function */ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class NullConsole extends _CustomConsole.default { + assert() {} + debug() {} + dir() {} + error() {} + info() {} + log() {} + time() {} + timeEnd() {} + timeLog() {} + trace() {} + warn() {} + group() {} + groupCollapsed() {} + groupEnd() {} +} +exports.default = NullConsole; diff --git a/node_modules/@jest/console/build/getConsoleOutput.js b/node_modules/@jest/console/build/getConsoleOutput.js new file mode 100644 index 0000000..821ecd3 --- /dev/null +++ b/node_modules/@jest/console/build/getConsoleOutput.js @@ -0,0 +1,70 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getConsoleOutput; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getConsoleOutput(buffer, config, globalConfig) { + const TITLE_INDENT = + globalConfig.verbose === true ? ' '.repeat(2) : ' '.repeat(4); + const CONSOLE_INDENT = TITLE_INDENT + ' '.repeat(2); + const logEntries = buffer.reduce((output, {type, message, origin}) => { + message = message + .split(/\n/) + .map(line => CONSOLE_INDENT + line) + .join('\n'); + let typeMessage = `console.${type}`; + let noStackTrace = true; + let noCodeFrame = true; + if (type === 'warn') { + message = _chalk().default.yellow(message); + typeMessage = _chalk().default.yellow(typeMessage); + noStackTrace = globalConfig?.noStackTrace ?? false; + noCodeFrame = false; + } else if (type === 'error') { + message = _chalk().default.red(message); + typeMessage = _chalk().default.red(typeMessage); + noStackTrace = globalConfig?.noStackTrace ?? false; + noCodeFrame = false; + } + const options = { + noCodeFrame, + noStackTrace + }; + const formattedStackTrace = (0, _jestMessageUtil().formatStackTrace)( + origin, + config, + options + ); + return `${ + output + TITLE_INDENT + _chalk().default.dim(typeMessage) + }\n${message.trimRight()}\n${_chalk().default.dim( + formattedStackTrace.trimRight() + )}\n\n`; + }, ''); + return `${logEntries.trimRight()}\n`; +} diff --git a/node_modules/@jest/console/build/index.d.ts b/node_modules/@jest/console/build/index.d.ts new file mode 100644 index 0000000..b679447 --- /dev/null +++ b/node_modules/@jest/console/build/index.d.ts @@ -0,0 +1,131 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import type {Config} from '@jest/types'; +import {Console as Console_2} from 'console'; +import {InspectOptions} from 'util'; +import {StackTraceConfig} from 'jest-message-util'; + +export declare class BufferedConsole extends Console_2 { + private readonly _buffer; + private _counters; + private _timers; + private _groupDepth; + Console: typeof Console_2; + constructor(); + static write( + this: void, + buffer: ConsoleBuffer, + type: LogType, + message: LogMessage, + level?: number | null, + ): ConsoleBuffer; + private _log; + assert(value: unknown, message?: string | Error): void; + count(label?: string): void; + countReset(label?: string): void; + debug(firstArg: unknown, ...rest: Array): void; + dir(firstArg: unknown, options?: InspectOptions): void; + dirxml(firstArg: unknown, ...rest: Array): void; + error(firstArg: unknown, ...rest: Array): void; + group(title?: string, ...rest: Array): void; + groupCollapsed(title?: string, ...rest: Array): void; + groupEnd(): void; + info(firstArg: unknown, ...rest: Array): void; + log(firstArg: unknown, ...rest: Array): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: Array): void; + warn(firstArg: unknown, ...rest: Array): void; + getBuffer(): ConsoleBuffer | undefined; +} + +export declare type ConsoleBuffer = Array; + +export declare class CustomConsole extends Console_2 { + private readonly _stdout; + private readonly _stderr; + private readonly _formatBuffer; + private _counters; + private _timers; + private _groupDepth; + Console: typeof Console_2; + constructor( + stdout: NodeJS.WriteStream, + stderr: NodeJS.WriteStream, + formatBuffer?: Formatter, + ); + private _log; + private _logError; + assert(value: unknown, message?: string | Error): asserts value; + count(label?: string): void; + countReset(label?: string): void; + debug(firstArg: unknown, ...args: Array): void; + dir(firstArg: unknown, options?: InspectOptions): void; + dirxml(firstArg: unknown, ...args: Array): void; + error(firstArg: unknown, ...args: Array): void; + group(title?: string, ...args: Array): void; + groupCollapsed(title?: string, ...args: Array): void; + groupEnd(): void; + info(firstArg: unknown, ...args: Array): void; + log(firstArg: unknown, ...args: Array): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: Array): void; + warn(firstArg: unknown, ...args: Array): void; + getBuffer(): undefined; +} + +declare type Formatter = (type: LogType, message: LogMessage) => string; + +export declare function getConsoleOutput( + buffer: ConsoleBuffer, + config: StackTraceConfig, + globalConfig: Config.GlobalConfig, +): string; + +export declare type LogEntry = { + message: LogMessage; + origin: string; + type: LogType; +}; + +export declare type LogMessage = string; + +export declare type LogType = + | 'assert' + | 'count' + | 'debug' + | 'dir' + | 'dirxml' + | 'error' + | 'group' + | 'groupCollapsed' + | 'info' + | 'log' + | 'time' + | 'warn'; + +export declare class NullConsole extends CustomConsole { + assert(): void; + debug(): void; + dir(): void; + error(): void; + info(): void; + log(): void; + time(): void; + timeEnd(): void; + timeLog(): void; + trace(): void; + warn(): void; + group(): void; + groupCollapsed(): void; + groupEnd(): void; +} + +export {}; diff --git a/node_modules/@jest/console/build/index.js b/node_modules/@jest/console/build/index.js new file mode 100644 index 0000000..6383b61 --- /dev/null +++ b/node_modules/@jest/console/build/index.js @@ -0,0 +1,36 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'BufferedConsole', { + enumerable: true, + get: function () { + return _BufferedConsole.default; + } +}); +Object.defineProperty(exports, 'CustomConsole', { + enumerable: true, + get: function () { + return _CustomConsole.default; + } +}); +Object.defineProperty(exports, 'NullConsole', { + enumerable: true, + get: function () { + return _NullConsole.default; + } +}); +Object.defineProperty(exports, 'getConsoleOutput', { + enumerable: true, + get: function () { + return _getConsoleOutput.default; + } +}); +var _BufferedConsole = _interopRequireDefault(require('./BufferedConsole')); +var _CustomConsole = _interopRequireDefault(require('./CustomConsole')); +var _NullConsole = _interopRequireDefault(require('./NullConsole')); +var _getConsoleOutput = _interopRequireDefault(require('./getConsoleOutput')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} diff --git a/node_modules/@jest/console/build/types.js b/node_modules/@jest/console/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/console/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/console/package.json b/node_modules/@jest/console/package.json new file mode 100644 index 0000000..f2d3bbe --- /dev/null +++ b/node_modules/@jest/console/package.json @@ -0,0 +1,37 @@ +{ + "name": "@jest/console", + "version": "29.2.1", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-console" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/types": "^29.2.1", + "@types/node": "*", + "chalk": "^4.0.0", + "jest-message-util": "^29.2.1", + "jest-util": "^29.2.1", + "slash": "^3.0.0" + }, + "devDependencies": { + "@jest/test-utils": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "4551c0fdd4d25b7206824957c7bcc6baf61e63bf" +} diff --git a/node_modules/@jest/core/LICENSE b/node_modules/@jest/core/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/core/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/core/README.md b/node_modules/@jest/core/README.md new file mode 100644 index 0000000..e5852b6 --- /dev/null +++ b/node_modules/@jest/core/README.md @@ -0,0 +1,3 @@ +# @jest/core + +Jest is currently working on providing a programmatic API. This is under development, and usage of this package directly is currently not supported. diff --git a/node_modules/@jest/core/build/FailedTestsCache.js b/node_modules/@jest/core/build/FailedTestsCache.js new file mode 100644 index 0000000..ccf0296 --- /dev/null +++ b/node_modules/@jest/core/build/FailedTestsCache.js @@ -0,0 +1,38 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class FailedTestsCache { + _enabledTestsMap; + filterTests(tests) { + const enabledTestsMap = this._enabledTestsMap; + if (!enabledTestsMap) { + return tests; + } + return tests.filter(testResult => enabledTestsMap[testResult.path]); + } + setTestResults(testResults) { + this._enabledTestsMap = (testResults || []) + .filter(testResult => testResult.numFailingTests) + .reduce((suiteMap, testResult) => { + suiteMap[testResult.testFilePath] = testResult.testResults + .filter(test => test.status === 'failed') + .reduce((testMap, test) => { + testMap[test.fullName] = true; + return testMap; + }, {}); + return suiteMap; + }, {}); + this._enabledTestsMap = Object.freeze(this._enabledTestsMap); + } +} +exports.default = FailedTestsCache; diff --git a/node_modules/@jest/core/build/FailedTestsInteractiveMode.js b/node_modules/@jest/core/build/FailedTestsInteractiveMode.js new file mode 100644 index 0000000..7a5daa0 --- /dev/null +++ b/node_modules/@jest/core/build/FailedTestsInteractiveMode.js @@ -0,0 +1,195 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _ansiEscapes() { + const data = _interopRequireDefault(require('ansi-escapes')); + _ansiEscapes = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const {ARROW, CLEAR} = _jestUtil().specialChars; +function describeKey(key, description) { + return `${_chalk().default.dim( + `${ARROW}Press` + )} ${key} ${_chalk().default.dim(description)}`; +} +const TestProgressLabel = _chalk().default.bold('Interactive Test Progress'); +class FailedTestsInteractiveMode { + _isActive = false; + _countPaths = 0; + _skippedNum = 0; + _testAssertions = []; + _updateTestRunnerConfig; + constructor(_pipe) { + this._pipe = _pipe; + } + isActive() { + return this._isActive; + } + put(key) { + switch (key) { + case 's': + if (this._skippedNum === this._testAssertions.length) { + break; + } + this._skippedNum += 1; + // move skipped test to the end + this._testAssertions.push(this._testAssertions.shift()); + if (this._testAssertions.length - this._skippedNum > 0) { + this._run(); + } else { + this._drawUIDoneWithSkipped(); + } + break; + case 'q': + case _jestWatcher().KEYS.ESCAPE: + this.abort(); + break; + case 'r': + this.restart(); + break; + case _jestWatcher().KEYS.ENTER: + if (this._testAssertions.length === 0) { + this.abort(); + } else { + this._run(); + } + break; + default: + } + } + run(failedTestAssertions, updateConfig) { + if (failedTestAssertions.length === 0) return; + this._testAssertions = [...failedTestAssertions]; + this._countPaths = this._testAssertions.length; + this._updateTestRunnerConfig = updateConfig; + this._isActive = true; + this._run(); + } + updateWithResults(results) { + if (!results.snapshot.failure && results.numFailedTests > 0) { + return this._drawUIOverlay(); + } + this._testAssertions.shift(); + if (this._testAssertions.length === 0) { + return this._drawUIOverlay(); + } + + // Go to the next test + return this._run(); + } + _clearTestSummary() { + this._pipe.write(_ansiEscapes().default.cursorUp(6)); + this._pipe.write(_ansiEscapes().default.eraseDown); + } + _drawUIDone() { + this._pipe.write(CLEAR); + const messages = [ + _chalk().default.bold('Watch Usage'), + describeKey('Enter', 'to return to watch mode.') + ]; + this._pipe.write(`${messages.join('\n')}\n`); + } + _drawUIDoneWithSkipped() { + this._pipe.write(CLEAR); + let stats = `${(0, _jestUtil().pluralize)( + 'test', + this._countPaths + )} reviewed`; + if (this._skippedNum > 0) { + const skippedText = _chalk().default.bold.yellow( + `${(0, _jestUtil().pluralize)('test', this._skippedNum)} skipped` + ); + stats = `${stats}, ${skippedText}`; + } + const message = [ + TestProgressLabel, + `${ARROW}${stats}`, + '\n', + _chalk().default.bold('Watch Usage'), + describeKey('r', 'to restart Interactive Mode.'), + describeKey('q', 'to quit Interactive Mode.'), + describeKey('Enter', 'to return to watch mode.') + ]; + this._pipe.write(`\n${message.join('\n')}`); + } + _drawUIProgress() { + this._clearTestSummary(); + const numPass = this._countPaths - this._testAssertions.length; + const numRemaining = this._countPaths - numPass - this._skippedNum; + let stats = `${(0, _jestUtil().pluralize)('test', numRemaining)} remaining`; + if (this._skippedNum > 0) { + const skippedText = _chalk().default.bold.yellow( + `${(0, _jestUtil().pluralize)('test', this._skippedNum)} skipped` + ); + stats = `${stats}, ${skippedText}`; + } + const message = [ + TestProgressLabel, + `${ARROW}${stats}`, + '\n', + _chalk().default.bold('Watch Usage'), + describeKey('s', 'to skip the current test.'), + describeKey('q', 'to quit Interactive Mode.'), + describeKey('Enter', 'to return to watch mode.') + ]; + this._pipe.write(`\n${message.join('\n')}`); + } + _drawUIOverlay() { + if (this._testAssertions.length === 0) return this._drawUIDone(); + return this._drawUIProgress(); + } + _run() { + if (this._updateTestRunnerConfig) { + this._updateTestRunnerConfig(this._testAssertions[0]); + } + } + abort() { + this._isActive = false; + this._skippedNum = 0; + if (this._updateTestRunnerConfig) { + this._updateTestRunnerConfig(); + } + } + restart() { + this._skippedNum = 0; + this._countPaths = this._testAssertions.length; + this._run(); + } +} +exports.default = FailedTestsInteractiveMode; diff --git a/node_modules/@jest/core/build/ReporterDispatcher.js b/node_modules/@jest/core/build/ReporterDispatcher.js new file mode 100644 index 0000000..577b94b --- /dev/null +++ b/node_modules/@jest/core/build/ReporterDispatcher.js @@ -0,0 +1,80 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class ReporterDispatcher { + _reporters; + constructor() { + this._reporters = []; + } + register(reporter) { + this._reporters.push(reporter); + } + unregister(reporterConstructor) { + this._reporters = this._reporters.filter( + reporter => !(reporter instanceof reporterConstructor) + ); + } + async onTestFileResult(test, testResult, results) { + for (const reporter of this._reporters) { + if (reporter.onTestFileResult) { + await reporter.onTestFileResult(test, testResult, results); + } else if (reporter.onTestResult) { + await reporter.onTestResult(test, testResult, results); + } + } + + // Release memory if unused later. + testResult.coverage = undefined; + testResult.console = undefined; + } + async onTestFileStart(test) { + for (const reporter of this._reporters) { + if (reporter.onTestFileStart) { + await reporter.onTestFileStart(test); + } else if (reporter.onTestStart) { + await reporter.onTestStart(test); + } + } + } + async onRunStart(results, options) { + for (const reporter of this._reporters) { + reporter.onRunStart && (await reporter.onRunStart(results, options)); + } + } + async onTestCaseResult(test, testCaseResult) { + for (const reporter of this._reporters) { + if (reporter.onTestCaseResult) { + await reporter.onTestCaseResult(test, testCaseResult); + } + } + } + async onRunComplete(testContexts, results) { + for (const reporter of this._reporters) { + if (reporter.onRunComplete) { + await reporter.onRunComplete(testContexts, results); + } + } + } + + // Return a list of last errors for every reporter + getErrors() { + return this._reporters.reduce((list, reporter) => { + const error = reporter.getLastError && reporter.getLastError(); + return error ? list.concat(error) : list; + }, []); + } + hasErrors() { + return this.getErrors().length !== 0; + } +} +exports.default = ReporterDispatcher; diff --git a/node_modules/@jest/core/build/SearchSource.js b/node_modules/@jest/core/build/SearchSource.js new file mode 100644 index 0000000..5812936 --- /dev/null +++ b/node_modules/@jest/core/build/SearchSource.js @@ -0,0 +1,408 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function os() { + const data = _interopRequireWildcard(require('os')); + os = function () { + return data; + }; + return data; +} +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _micromatch() { + const data = _interopRequireDefault(require('micromatch')); + _micromatch = function () { + return data; + }; + return data; +} +function _jestConfig() { + const data = require('jest-config'); + _jestConfig = function () { + return data; + }; + return data; +} +function _jestRegexUtil() { + const data = require('jest-regex-util'); + _jestRegexUtil = function () { + return data; + }; + return data; +} +function _jestResolveDependencies() { + const data = require('jest-resolve-dependencies'); + _jestResolveDependencies = function () { + return data; + }; + return data; +} +function _jestSnapshot() { + const data = require('jest-snapshot'); + _jestSnapshot = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const regexToMatcher = testRegex => { + const regexes = testRegex.map(testRegex => new RegExp(testRegex)); + return path => + regexes.some(regex => { + const result = regex.test(path); + + // prevent stateful regexes from breaking, just in case + regex.lastIndex = 0; + return result; + }); +}; +const toTests = (context, tests) => + tests.map(path => ({ + context, + duration: undefined, + path + })); +const hasSCM = changedFilesInfo => { + const {repos} = changedFilesInfo; + // no SCM (git/hg/...) is found in any of the roots. + const noSCM = Object.values(repos).every(scm => scm.size === 0); + return !noSCM; +}; +class SearchSource { + _context; + _dependencyResolver; + _testPathCases = []; + constructor(context) { + const {config} = context; + this._context = context; + this._dependencyResolver = null; + const rootPattern = new RegExp( + config.roots + .map(dir => (0, _jestRegexUtil().escapePathForRegex)(dir + path().sep)) + .join('|') + ); + this._testPathCases.push({ + isMatch: path => rootPattern.test(path), + stat: 'roots' + }); + if (config.testMatch.length) { + this._testPathCases.push({ + isMatch: (0, _jestUtil().globsToMatcher)(config.testMatch), + stat: 'testMatch' + }); + } + if (config.testPathIgnorePatterns.length) { + const testIgnorePatternsRegex = new RegExp( + config.testPathIgnorePatterns.join('|') + ); + this._testPathCases.push({ + isMatch: path => !testIgnorePatternsRegex.test(path), + stat: 'testPathIgnorePatterns' + }); + } + if (config.testRegex.length) { + this._testPathCases.push({ + isMatch: regexToMatcher(config.testRegex), + stat: 'testRegex' + }); + } + } + async _getOrBuildDependencyResolver() { + if (!this._dependencyResolver) { + this._dependencyResolver = + new (_jestResolveDependencies().DependencyResolver)( + this._context.resolver, + this._context.hasteFS, + await (0, _jestSnapshot().buildSnapshotResolver)(this._context.config) + ); + } + return this._dependencyResolver; + } + _filterTestPathsWithStats(allPaths, testPathPattern) { + const data = { + stats: { + roots: 0, + testMatch: 0, + testPathIgnorePatterns: 0, + testRegex: 0 + }, + tests: [], + total: allPaths.length + }; + const testCases = Array.from(this._testPathCases); // clone + if (testPathPattern) { + const regex = (0, _jestUtil().testPathPatternToRegExp)(testPathPattern); + testCases.push({ + isMatch: path => regex.test(path), + stat: 'testPathPattern' + }); + data.stats.testPathPattern = 0; + } + data.tests = allPaths.filter(test => { + let filterResult = true; + for (const {isMatch, stat} of testCases) { + if (isMatch(test.path)) { + data.stats[stat]++; + } else { + filterResult = false; + } + } + return filterResult; + }); + return data; + } + _getAllTestPaths(testPathPattern) { + return this._filterTestPathsWithStats( + toTests(this._context, this._context.hasteFS.getAllFiles()), + testPathPattern + ); + } + isTestFilePath(path) { + return this._testPathCases.every(testCase => testCase.isMatch(path)); + } + findMatchingTests(testPathPattern) { + return this._getAllTestPaths(testPathPattern); + } + async findRelatedTests(allPaths, collectCoverage) { + const dependencyResolver = await this._getOrBuildDependencyResolver(); + if (!collectCoverage) { + return { + tests: toTests( + this._context, + dependencyResolver.resolveInverse( + allPaths, + this.isTestFilePath.bind(this), + { + skipNodeResolution: this._context.config.skipNodeResolution + } + ) + ) + }; + } + const testModulesMap = dependencyResolver.resolveInverseModuleMap( + allPaths, + this.isTestFilePath.bind(this), + { + skipNodeResolution: this._context.config.skipNodeResolution + } + ); + const allPathsAbsolute = Array.from(allPaths).map(p => path().resolve(p)); + const collectCoverageFrom = new Set(); + testModulesMap.forEach(testModule => { + if (!testModule.dependencies) { + return; + } + testModule.dependencies.forEach(p => { + if (!allPathsAbsolute.includes(p)) { + return; + } + const filename = (0, _jestConfig().replaceRootDirInPath)( + this._context.config.rootDir, + p + ); + collectCoverageFrom.add( + path().isAbsolute(filename) + ? path().relative(this._context.config.rootDir, filename) + : filename + ); + }); + }); + return { + collectCoverageFrom, + tests: toTests( + this._context, + testModulesMap.map(testModule => testModule.file) + ) + }; + } + findTestsByPaths(paths) { + return { + tests: toTests( + this._context, + paths + .map(p => path().resolve(this._context.config.cwd, p)) + .filter(this.isTestFilePath.bind(this)) + ) + }; + } + async findRelatedTestsFromPattern(paths, collectCoverage) { + if (Array.isArray(paths) && paths.length) { + const resolvedPaths = paths.map(p => + path().resolve(this._context.config.cwd, p) + ); + return this.findRelatedTests(new Set(resolvedPaths), collectCoverage); + } + return { + tests: [] + }; + } + async findTestRelatedToChangedFiles(changedFilesInfo, collectCoverage) { + if (!hasSCM(changedFilesInfo)) { + return { + noSCM: true, + tests: [] + }; + } + const {changedFiles} = changedFilesInfo; + return this.findRelatedTests(changedFiles, collectCoverage); + } + async _getTestPaths(globalConfig, changedFiles) { + if (globalConfig.onlyChanged) { + if (!changedFiles) { + throw new Error('Changed files must be set when running with -o.'); + } + return this.findTestRelatedToChangedFiles( + changedFiles, + globalConfig.collectCoverage + ); + } + let paths = globalConfig.nonFlagArgs; + if (globalConfig.findRelatedTests && 'win32' === os().platform()) { + paths = this.filterPathsWin32(paths); + } + if (globalConfig.runTestsByPath && paths && paths.length) { + return this.findTestsByPaths(paths); + } else if (globalConfig.findRelatedTests && paths && paths.length) { + return this.findRelatedTestsFromPattern( + paths, + globalConfig.collectCoverage + ); + } else if (globalConfig.testPathPattern != null) { + return this.findMatchingTests(globalConfig.testPathPattern); + } else { + return { + tests: [] + }; + } + } + filterPathsWin32(paths) { + const allFiles = this._context.hasteFS.getAllFiles(); + const options = { + nocase: true, + windows: false + }; + function normalizePosix(filePath) { + return filePath.replace(/\\/g, '/'); + } + paths = paths + .map(p => { + // micromatch works with forward slashes: https://github.com/micromatch/micromatch#backslashes + const normalizedPath = normalizePosix( + path().resolve(this._context.config.cwd, p) + ); + const match = (0, _micromatch().default)( + allFiles.map(normalizePosix), + normalizedPath, + options + ); + return match[0]; + }) + .filter(Boolean) + .map(p => path().resolve(p)); + return paths; + } + async getTestPaths(globalConfig, changedFiles, filter) { + const searchResult = await this._getTestPaths(globalConfig, changedFiles); + const filterPath = globalConfig.filter; + if (filter) { + const tests = searchResult.tests; + const filterResult = await filter(tests.map(test => test.path)); + if (!Array.isArray(filterResult.filtered)) { + throw new Error( + `Filter ${filterPath} did not return a valid test list` + ); + } + const filteredSet = new Set( + filterResult.filtered.map(result => result.test) + ); + return { + ...searchResult, + tests: tests.filter(test => filteredSet.has(test.path)) + }; + } + return searchResult; + } + async findRelatedSourcesFromTestsInChangedFiles(changedFilesInfo) { + if (!hasSCM(changedFilesInfo)) { + return []; + } + const {changedFiles} = changedFilesInfo; + const dependencyResolver = await this._getOrBuildDependencyResolver(); + const relatedSourcesSet = new Set(); + changedFiles.forEach(filePath => { + if (this.isTestFilePath(filePath)) { + const sourcePaths = dependencyResolver.resolve(filePath, { + skipNodeResolution: this._context.config.skipNodeResolution + }); + sourcePaths.forEach(sourcePath => relatedSourcesSet.add(sourcePath)); + } + }); + return Array.from(relatedSourcesSet); + } +} +exports.default = SearchSource; diff --git a/node_modules/@jest/core/build/SnapshotInteractiveMode.js b/node_modules/@jest/core/build/SnapshotInteractiveMode.js new file mode 100644 index 0000000..6e1f2c5 --- /dev/null +++ b/node_modules/@jest/core/build/SnapshotInteractiveMode.js @@ -0,0 +1,238 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _ansiEscapes() { + const data = _interopRequireDefault(require('ansi-escapes')); + _ansiEscapes = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const {ARROW, CLEAR} = _jestUtil().specialChars; +class SnapshotInteractiveMode { + _pipe; + _isActive; + _updateTestRunnerConfig; + _testAssertions; + _countPaths; + _skippedNum; + constructor(pipe) { + this._pipe = pipe; + this._isActive = false; + this._skippedNum = 0; + } + isActive() { + return this._isActive; + } + getSkippedNum() { + return this._skippedNum; + } + _clearTestSummary() { + this._pipe.write(_ansiEscapes().default.cursorUp(6)); + this._pipe.write(_ansiEscapes().default.eraseDown); + } + _drawUIProgress() { + this._clearTestSummary(); + const numPass = this._countPaths - this._testAssertions.length; + const numRemaining = this._countPaths - numPass - this._skippedNum; + let stats = _chalk().default.bold.dim( + `${(0, _jestUtil().pluralize)('snapshot', numRemaining)} remaining` + ); + if (numPass) { + stats += `, ${_chalk().default.bold.green( + `${(0, _jestUtil().pluralize)('snapshot', numPass)} updated` + )}`; + } + if (this._skippedNum) { + stats += `, ${_chalk().default.bold.yellow( + `${(0, _jestUtil().pluralize)('snapshot', this._skippedNum)} skipped` + )}`; + } + const messages = [ + `\n${_chalk().default.bold('Interactive Snapshot Progress')}`, + ARROW + stats, + `\n${_chalk().default.bold('Watch Usage')}`, + `${_chalk().default.dim(`${ARROW}Press `)}u${_chalk().default.dim( + ' to update failing snapshots for this test.' + )}`, + `${_chalk().default.dim(`${ARROW}Press `)}s${_chalk().default.dim( + ' to skip the current test.' + )}`, + `${_chalk().default.dim(`${ARROW}Press `)}q${_chalk().default.dim( + ' to quit Interactive Snapshot Mode.' + )}`, + `${_chalk().default.dim(`${ARROW}Press `)}Enter${_chalk().default.dim( + ' to trigger a test run.' + )}` + ]; + this._pipe.write(`${messages.filter(Boolean).join('\n')}\n`); + } + _drawUIDoneWithSkipped() { + this._pipe.write(CLEAR); + const numPass = this._countPaths - this._testAssertions.length; + let stats = _chalk().default.bold.dim( + `${(0, _jestUtil().pluralize)('snapshot', this._countPaths)} reviewed` + ); + if (numPass) { + stats += `, ${_chalk().default.bold.green( + `${(0, _jestUtil().pluralize)('snapshot', numPass)} updated` + )}`; + } + if (this._skippedNum) { + stats += `, ${_chalk().default.bold.yellow( + `${(0, _jestUtil().pluralize)('snapshot', this._skippedNum)} skipped` + )}`; + } + const messages = [ + `\n${_chalk().default.bold('Interactive Snapshot Result')}`, + ARROW + stats, + `\n${_chalk().default.bold('Watch Usage')}`, + `${_chalk().default.dim(`${ARROW}Press `)}r${_chalk().default.dim( + ' to restart Interactive Snapshot Mode.' + )}`, + `${_chalk().default.dim(`${ARROW}Press `)}q${_chalk().default.dim( + ' to quit Interactive Snapshot Mode.' + )}` + ]; + this._pipe.write(`${messages.filter(Boolean).join('\n')}\n`); + } + _drawUIDone() { + this._pipe.write(CLEAR); + const numPass = this._countPaths - this._testAssertions.length; + let stats = _chalk().default.bold.dim( + `${(0, _jestUtil().pluralize)('snapshot', this._countPaths)} reviewed` + ); + if (numPass) { + stats += `, ${_chalk().default.bold.green( + `${(0, _jestUtil().pluralize)('snapshot', numPass)} updated` + )}`; + } + const messages = [ + `\n${_chalk().default.bold('Interactive Snapshot Result')}`, + ARROW + stats, + `\n${_chalk().default.bold('Watch Usage')}`, + `${_chalk().default.dim(`${ARROW}Press `)}Enter${_chalk().default.dim( + ' to return to watch mode.' + )}` + ]; + this._pipe.write(`${messages.filter(Boolean).join('\n')}\n`); + } + _drawUIOverlay() { + if (this._testAssertions.length === 0) { + return this._drawUIDone(); + } + if (this._testAssertions.length - this._skippedNum === 0) { + return this._drawUIDoneWithSkipped(); + } + return this._drawUIProgress(); + } + put(key) { + switch (key) { + case 's': + if (this._skippedNum === this._testAssertions.length) break; + this._skippedNum += 1; + + // move skipped test to the end + this._testAssertions.push(this._testAssertions.shift()); + if (this._testAssertions.length - this._skippedNum > 0) { + this._run(false); + } else { + this._drawUIDoneWithSkipped(); + } + break; + case 'u': + this._run(true); + break; + case 'q': + case _jestWatcher().KEYS.ESCAPE: + this.abort(); + break; + case 'r': + this.restart(); + break; + case _jestWatcher().KEYS.ENTER: + if (this._testAssertions.length === 0) { + this.abort(); + } else { + this._run(false); + } + break; + default: + break; + } + } + abort() { + this._isActive = false; + this._skippedNum = 0; + this._updateTestRunnerConfig(null, false); + } + restart() { + this._skippedNum = 0; + this._countPaths = this._testAssertions.length; + this._run(false); + } + updateWithResults(results) { + const hasSnapshotFailure = !!results.snapshot.failure; + if (hasSnapshotFailure) { + this._drawUIOverlay(); + return; + } + this._testAssertions.shift(); + if (this._testAssertions.length - this._skippedNum === 0) { + this._drawUIOverlay(); + return; + } + + // Go to the next test + this._run(false); + } + _run(shouldUpdateSnapshot) { + const testAssertion = this._testAssertions[0]; + this._updateTestRunnerConfig(testAssertion, shouldUpdateSnapshot); + } + run(failedSnapshotTestAssertions, onConfigChange) { + if (!failedSnapshotTestAssertions.length) { + return; + } + this._testAssertions = [...failedSnapshotTestAssertions]; + this._countPaths = this._testAssertions.length; + this._updateTestRunnerConfig = onConfigChange; + this._isActive = true; + this._run(false); + } +} +exports.default = SnapshotInteractiveMode; diff --git a/node_modules/@jest/core/build/TestNamePatternPrompt.js b/node_modules/@jest/core/build/TestNamePatternPrompt.js new file mode 100644 index 0000000..30f930a --- /dev/null +++ b/node_modules/@jest/core/build/TestNamePatternPrompt.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class TestNamePatternPrompt extends _jestWatcher().PatternPrompt { + constructor(pipe, prompt) { + super(pipe, prompt, 'tests'); + } + _onChange(pattern, options) { + super._onChange(pattern, options); + this._printPrompt(pattern); + } + _printPrompt(pattern) { + const pipe = this._pipe; + (0, _jestWatcher().printPatternCaret)(pattern, pipe); + (0, _jestWatcher().printRestoredPatternCaret)( + pattern, + this._currentUsageRows, + pipe + ); + } +} +exports.default = TestNamePatternPrompt; diff --git a/node_modules/@jest/core/build/TestPathPatternPrompt.js b/node_modules/@jest/core/build/TestPathPatternPrompt.js new file mode 100644 index 0000000..abd351f --- /dev/null +++ b/node_modules/@jest/core/build/TestPathPatternPrompt.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class TestPathPatternPrompt extends _jestWatcher().PatternPrompt { + constructor(pipe, prompt) { + super(pipe, prompt, 'filenames'); + } + _onChange(pattern, options) { + super._onChange(pattern, options); + this._printPrompt(pattern); + } + _printPrompt(pattern) { + const pipe = this._pipe; + (0, _jestWatcher().printPatternCaret)(pattern, pipe); + (0, _jestWatcher().printRestoredPatternCaret)( + pattern, + this._currentUsageRows, + pipe + ); + } +} +exports.default = TestPathPatternPrompt; diff --git a/node_modules/@jest/core/build/TestScheduler.js b/node_modules/@jest/core/build/TestScheduler.js new file mode 100644 index 0000000..e86956c --- /dev/null +++ b/node_modules/@jest/core/build/TestScheduler.js @@ -0,0 +1,451 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.createTestScheduler = createTestScheduler; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _ciInfo() { + const data = require('ci-info'); + _ciInfo = function () { + return data; + }; + return data; +} +function _exit() { + const data = _interopRequireDefault(require('exit')); + _exit = function () { + return data; + }; + return data; +} +function _reporters() { + const data = require('@jest/reporters'); + _reporters = function () { + return data; + }; + return data; +} +function _testResult() { + const data = require('@jest/test-result'); + _testResult = function () { + return data; + }; + return data; +} +function _transform() { + const data = require('@jest/transform'); + _transform = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +function _jestSnapshot() { + const data = require('jest-snapshot'); + _jestSnapshot = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _ReporterDispatcher = _interopRequireDefault( + require('./ReporterDispatcher') +); +var _testSchedulerHelper = require('./testSchedulerHelper'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +async function createTestScheduler(globalConfig, context) { + const scheduler = new TestScheduler(globalConfig, context); + await scheduler._setupReporters(); + return scheduler; +} +class TestScheduler { + _context; + _dispatcher; + _globalConfig; + constructor(globalConfig, context) { + this._context = context; + this._dispatcher = new _ReporterDispatcher.default(); + this._globalConfig = globalConfig; + } + addReporter(reporter) { + this._dispatcher.register(reporter); + } + removeReporter(reporterConstructor) { + this._dispatcher.unregister(reporterConstructor); + } + async scheduleTests(tests, watcher) { + const onTestFileStart = this._dispatcher.onTestFileStart.bind( + this._dispatcher + ); + const timings = []; + const testContexts = new Set(); + tests.forEach(test => { + testContexts.add(test.context); + if (test.duration) { + timings.push(test.duration); + } + }); + const aggregatedResults = createAggregatedResults(tests.length); + const estimatedTime = Math.ceil( + getEstimatedTime(timings, this._globalConfig.maxWorkers) / 1000 + ); + const runInBand = (0, _testSchedulerHelper.shouldRunInBand)( + tests, + timings, + this._globalConfig + ); + const onResult = async (test, testResult) => { + if (watcher.isInterrupted()) { + return Promise.resolve(); + } + if (testResult.testResults.length === 0) { + const message = 'Your test suite must contain at least one test.'; + return onFailure(test, { + message, + stack: new Error(message).stack + }); + } + + // Throws when the context is leaked after executing a test. + if (testResult.leaks) { + const message = + `${_chalk().default.red.bold( + 'EXPERIMENTAL FEATURE!\n' + )}Your test suite is leaking memory. Please ensure all references are cleaned.\n` + + '\n' + + 'There is a number of things that can leak memory:\n' + + ' - Async operations that have not finished (e.g. fs.readFile).\n' + + ' - Timers not properly mocked (e.g. setInterval, setTimeout).\n' + + ' - Keeping references to the global scope.'; + return onFailure(test, { + message, + stack: new Error(message).stack + }); + } + (0, _testResult().addResult)(aggregatedResults, testResult); + await this._dispatcher.onTestFileResult( + test, + testResult, + aggregatedResults + ); + return this._bailIfNeeded(testContexts, aggregatedResults, watcher); + }; + const onFailure = async (test, error) => { + if (watcher.isInterrupted()) { + return; + } + const testResult = (0, _testResult().buildFailureTestResult)( + test.path, + error + ); + testResult.failureMessage = (0, _jestMessageUtil().formatExecError)( + testResult.testExecError, + test.context.config, + this._globalConfig, + test.path + ); + (0, _testResult().addResult)(aggregatedResults, testResult); + await this._dispatcher.onTestFileResult( + test, + testResult, + aggregatedResults + ); + }; + const updateSnapshotState = async () => { + const contextsWithSnapshotResolvers = await Promise.all( + Array.from(testContexts).map(async context => [ + context, + await (0, _jestSnapshot().buildSnapshotResolver)(context.config) + ]) + ); + contextsWithSnapshotResolvers.forEach(([context, snapshotResolver]) => { + const status = (0, _jestSnapshot().cleanup)( + context.hasteFS, + this._globalConfig.updateSnapshot, + snapshotResolver, + context.config.testPathIgnorePatterns + ); + aggregatedResults.snapshot.filesRemoved += status.filesRemoved; + aggregatedResults.snapshot.filesRemovedList = ( + aggregatedResults.snapshot.filesRemovedList || [] + ).concat(status.filesRemovedList); + }); + const updateAll = this._globalConfig.updateSnapshot === 'all'; + aggregatedResults.snapshot.didUpdate = updateAll; + aggregatedResults.snapshot.failure = !!( + !updateAll && + (aggregatedResults.snapshot.unchecked || + aggregatedResults.snapshot.unmatched || + aggregatedResults.snapshot.filesRemoved) + ); + }; + await this._dispatcher.onRunStart(aggregatedResults, { + estimatedTime, + showStatus: !runInBand + }); + const testRunners = Object.create(null); + const contextsByTestRunner = new WeakMap(); + try { + await Promise.all( + Array.from(testContexts).map(async context => { + const {config} = context; + if (!testRunners[config.runner]) { + const transformer = await (0, _transform().createScriptTransformer)( + config + ); + const Runner = await transformer.requireAndTranspileModule( + config.runner + ); + const runner = new Runner(this._globalConfig, { + changedFiles: this._context.changedFiles, + sourcesRelatedToTestsInChangedFiles: + this._context.sourcesRelatedToTestsInChangedFiles + }); + testRunners[config.runner] = runner; + contextsByTestRunner.set(runner, context); + } + }) + ); + const testsByRunner = this._partitionTests(testRunners, tests); + if (testsByRunner) { + try { + for (const runner of Object.keys(testRunners)) { + const testRunner = testRunners[runner]; + const context = contextsByTestRunner.get(testRunner); + invariant(context); + const tests = testsByRunner[runner]; + const testRunnerOptions = { + serial: runInBand || Boolean(testRunner.isSerial) + }; + if (testRunner.supportsEventEmitters) { + const unsubscribes = [ + testRunner.on('test-file-start', ([test]) => + onTestFileStart(test) + ), + testRunner.on('test-file-success', ([test, testResult]) => + onResult(test, testResult) + ), + testRunner.on('test-file-failure', ([test, error]) => + onFailure(test, error) + ), + testRunner.on( + 'test-case-result', + ([testPath, testCaseResult]) => { + const test = { + context, + path: testPath + }; + this._dispatcher.onTestCaseResult(test, testCaseResult); + } + ) + ]; + await testRunner.runTests(tests, watcher, testRunnerOptions); + unsubscribes.forEach(sub => sub()); + } else { + await testRunner.runTests( + tests, + watcher, + onTestFileStart, + onResult, + onFailure, + testRunnerOptions + ); + } + } + } catch (error) { + if (!watcher.isInterrupted()) { + throw error; + } + } + } + } catch (error) { + aggregatedResults.runExecError = buildExecError(error); + await this._dispatcher.onRunComplete(testContexts, aggregatedResults); + throw error; + } + await updateSnapshotState(); + aggregatedResults.wasInterrupted = watcher.isInterrupted(); + await this._dispatcher.onRunComplete(testContexts, aggregatedResults); + const anyTestFailures = !( + aggregatedResults.numFailedTests === 0 && + aggregatedResults.numRuntimeErrorTestSuites === 0 + ); + const anyReporterErrors = this._dispatcher.hasErrors(); + aggregatedResults.success = !( + anyTestFailures || + aggregatedResults.snapshot.failure || + anyReporterErrors + ); + return aggregatedResults; + } + _partitionTests(testRunners, tests) { + if (Object.keys(testRunners).length > 1) { + return tests.reduce((testRuns, test) => { + const runner = test.context.config.runner; + if (!testRuns[runner]) { + testRuns[runner] = []; + } + testRuns[runner].push(test); + return testRuns; + }, Object.create(null)); + } else if (tests.length > 0 && tests[0] != null) { + // If there is only one runner, don't partition the tests. + return Object.assign(Object.create(null), { + [tests[0].context.config.runner]: tests + }); + } else { + return null; + } + } + async _setupReporters() { + const {collectCoverage: coverage, notify, verbose} = this._globalConfig; + const reporters = this._globalConfig.reporters || [['default', {}]]; + let summary = false; + for (const [reporter, options] of reporters) { + switch (reporter) { + case 'default': + summary = true; + verbose + ? this.addReporter( + new (_reporters().VerboseReporter)(this._globalConfig) + ) + : this.addReporter( + new (_reporters().DefaultReporter)(this._globalConfig) + ); + break; + case 'github-actions': + _ciInfo().GITHUB_ACTIONS && + this.addReporter(new (_reporters().GitHubActionsReporter)()); + break; + case 'summary': + summary = true; + break; + default: + await this._addCustomReporter(reporter, options); + } + } + if (notify) { + this.addReporter( + new (_reporters().NotifyReporter)(this._globalConfig, this._context) + ); + } + if (coverage) { + this.addReporter( + new (_reporters().CoverageReporter)(this._globalConfig, this._context) + ); + } + if (summary) { + this.addReporter(new (_reporters().SummaryReporter)(this._globalConfig)); + } + } + async _addCustomReporter(reporter, options) { + try { + const Reporter = await (0, _jestUtil().requireOrImportModule)(reporter); + this.addReporter( + new Reporter(this._globalConfig, options, this._context) + ); + } catch (error) { + error.message = `An error occurred while adding the reporter at path "${_chalk().default.bold( + reporter + )}".\n${error instanceof Error ? error.message : ''}`; + throw error; + } + } + async _bailIfNeeded(testContexts, aggregatedResults, watcher) { + if ( + this._globalConfig.bail !== 0 && + aggregatedResults.numFailedTests >= this._globalConfig.bail + ) { + if (watcher.isWatchMode()) { + await watcher.setState({ + interrupted: true + }); + return; + } + try { + await this._dispatcher.onRunComplete(testContexts, aggregatedResults); + } finally { + const exitCode = this._globalConfig.testFailureExitCode; + (0, _exit().default)(exitCode); + } + } + } +} +function invariant(condition, message) { + if (!condition) { + throw new Error(message); + } +} +const createAggregatedResults = numTotalTestSuites => { + const result = (0, _testResult().makeEmptyAggregatedTestResult)(); + result.numTotalTestSuites = numTotalTestSuites; + result.startTime = Date.now(); + result.success = false; + return result; +}; +const getEstimatedTime = (timings, workers) => { + if (timings.length === 0) { + return 0; + } + const max = Math.max(...timings); + return timings.length <= workers + ? max + : Math.max(timings.reduce((sum, time) => sum + time) / workers, max); +}; +const strToError = errString => { + const {message, stack} = (0, _jestMessageUtil().separateMessageFromStack)( + errString + ); + if (stack.length > 0) { + return { + message, + stack + }; + } + const error = new (_jestUtil().ErrorWithStack)(message, buildExecError); + return { + message, + stack: error.stack || '' + }; +}; +const buildExecError = err => { + if (typeof err === 'string' || err == null) { + return strToError(err || 'Error'); + } + const anyErr = err; + if (typeof anyErr.message === 'string') { + if (typeof anyErr.stack === 'string' && anyErr.stack.length > 0) { + return anyErr; + } + return strToError(anyErr.message); + } + return strToError(JSON.stringify(err)); +}; diff --git a/node_modules/@jest/core/build/cli/index.js b/node_modules/@jest/core/build/cli/index.js new file mode 100644 index 0000000..6e54130 --- /dev/null +++ b/node_modules/@jest/core/build/cli/index.js @@ -0,0 +1,400 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.runCLI = runCLI; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _exit() { + const data = _interopRequireDefault(require('exit')); + _exit = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _console() { + const data = require('@jest/console'); + _console = function () { + return data; + }; + return data; +} +function _jestConfig() { + const data = require('jest-config'); + _jestConfig = function () { + return data; + }; + return data; +} +function _jestRuntime() { + const data = _interopRequireDefault(require('jest-runtime')); + _jestRuntime = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +var _collectHandles = require('../collectHandles'); +var _getChangedFilesPromise = _interopRequireDefault( + require('../getChangedFilesPromise') +); +var _getConfigsOfProjectsToRun = _interopRequireDefault( + require('../getConfigsOfProjectsToRun') +); +var _getProjectNamesMissingWarning = _interopRequireDefault( + require('../getProjectNamesMissingWarning') +); +var _getSelectProjectsMessage = _interopRequireDefault( + require('../getSelectProjectsMessage') +); +var _createContext = _interopRequireDefault(require('../lib/createContext')); +var _handleDeprecationWarnings = _interopRequireDefault( + require('../lib/handleDeprecationWarnings') +); +var _logDebugMessages = _interopRequireDefault( + require('../lib/logDebugMessages') +); +var _pluralize = _interopRequireDefault(require('../pluralize')); +var _runJest = _interopRequireDefault(require('../runJest')); +var _watch = _interopRequireDefault(require('../watch')); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const {print: preRunMessagePrint} = _jestUtil().preRunMessage; +async function runCLI(argv, projects) { + let results; + + // If we output a JSON object, we can't write anything to stdout, since + // it'll break the JSON structure and it won't be valid. + const outputStream = + argv.json || argv.useStderr ? process.stderr : process.stdout; + const {globalConfig, configs, hasDeprecationWarnings} = await (0, + _jestConfig().readConfigs)(argv, projects); + if (argv.debug) { + (0, _logDebugMessages.default)(globalConfig, configs, outputStream); + } + if (argv.showConfig) { + (0, _logDebugMessages.default)(globalConfig, configs, process.stdout); + (0, _exit().default)(0); + } + if (argv.clearCache) { + // stick in a Set to dedupe the deletions + new Set(configs.map(config => config.cacheDirectory)).forEach( + cacheDirectory => { + fs().rmSync(cacheDirectory, { + force: true, + recursive: true + }); + process.stdout.write(`Cleared ${cacheDirectory}\n`); + } + ); + (0, _exit().default)(0); + } + const configsOfProjectsToRun = (0, _getConfigsOfProjectsToRun.default)( + configs, + { + ignoreProjects: argv.ignoreProjects, + selectProjects: argv.selectProjects + } + ); + if (argv.selectProjects || argv.ignoreProjects) { + const namesMissingWarning = (0, _getProjectNamesMissingWarning.default)( + configs, + { + ignoreProjects: argv.ignoreProjects, + selectProjects: argv.selectProjects + } + ); + if (namesMissingWarning) { + outputStream.write(namesMissingWarning); + } + outputStream.write( + (0, _getSelectProjectsMessage.default)(configsOfProjectsToRun, { + ignoreProjects: argv.ignoreProjects, + selectProjects: argv.selectProjects + }) + ); + } + await _run10000( + globalConfig, + configsOfProjectsToRun, + hasDeprecationWarnings, + outputStream, + r => { + results = r; + } + ); + if (argv.watch || argv.watchAll) { + // If in watch mode, return the promise that will never resolve. + // If the watch mode is interrupted, watch should handle the process + // shutdown. + // eslint-disable-next-line @typescript-eslint/no-empty-function + return new Promise(() => {}); + } + if (!results) { + throw new Error( + 'AggregatedResult must be present after test run is complete' + ); + } + const {openHandles} = results; + if (openHandles && openHandles.length) { + const formatted = (0, _collectHandles.formatHandleErrors)( + openHandles, + configs[0] + ); + const openHandlesString = (0, _pluralize.default)( + 'open handle', + formatted.length, + 's' + ); + const message = + _chalk().default.red( + `\nJest has detected the following ${openHandlesString} potentially keeping Jest from exiting:\n\n` + ) + formatted.join('\n\n'); + console.error(message); + } + return { + globalConfig, + results + }; +} +const buildContextsAndHasteMaps = async ( + configs, + globalConfig, + outputStream +) => { + const hasteMapInstances = Array(configs.length); + const contexts = await Promise.all( + configs.map(async (config, index) => { + (0, _jestUtil().createDirectory)(config.cacheDirectory); + const hasteMapInstance = await _jestRuntime().default.createHasteMap( + config, + { + console: new (_console().CustomConsole)(outputStream, outputStream), + maxWorkers: Math.max( + 1, + Math.floor(globalConfig.maxWorkers / configs.length) + ), + resetCache: !config.cache, + watch: globalConfig.watch || globalConfig.watchAll, + watchman: globalConfig.watchman + } + ); + hasteMapInstances[index] = hasteMapInstance; + return (0, _createContext.default)( + config, + await hasteMapInstance.build() + ); + }) + ); + return { + contexts, + hasteMapInstances + }; +}; +const _run10000 = async ( + globalConfig, + configs, + hasDeprecationWarnings, + outputStream, + onComplete +) => { + // Queries to hg/git can take a while, so we need to start the process + // as soon as possible, so by the time we need the result it's already there. + const changedFilesPromise = (0, _getChangedFilesPromise.default)( + globalConfig, + configs + ); + + // Filter may need to do an HTTP call or something similar to setup. + // We will wait on an async response from this before using the filter. + let filter; + if (globalConfig.filter && !globalConfig.skipFilter) { + const rawFilter = require(globalConfig.filter); + let filterSetupPromise; + if (rawFilter.setup) { + // Wrap filter setup Promise to avoid "uncaught Promise" error. + // If an error is returned, we surface it in the return value. + filterSetupPromise = (async () => { + try { + await rawFilter.setup(); + } catch (err) { + return err; + } + return undefined; + })(); + } + filter = async testPaths => { + if (filterSetupPromise) { + // Expect an undefined return value unless there was an error. + const err = await filterSetupPromise; + if (err) { + throw err; + } + } + return rawFilter(testPaths); + }; + } + const {contexts, hasteMapInstances} = await buildContextsAndHasteMaps( + configs, + globalConfig, + outputStream + ); + globalConfig.watch || globalConfig.watchAll + ? await runWatch( + contexts, + configs, + hasDeprecationWarnings, + globalConfig, + outputStream, + hasteMapInstances, + filter + ) + : await runWithoutWatch( + globalConfig, + contexts, + outputStream, + onComplete, + changedFilesPromise, + filter + ); +}; +const runWatch = async ( + contexts, + _configs, + hasDeprecationWarnings, + globalConfig, + outputStream, + hasteMapInstances, + filter +) => { + if (hasDeprecationWarnings) { + try { + await (0, _handleDeprecationWarnings.default)( + outputStream, + process.stdin + ); + return await (0, _watch.default)( + globalConfig, + contexts, + outputStream, + hasteMapInstances, + undefined, + undefined, + filter + ); + } catch { + (0, _exit().default)(0); + } + } + return (0, _watch.default)( + globalConfig, + contexts, + outputStream, + hasteMapInstances, + undefined, + undefined, + filter + ); +}; +const runWithoutWatch = async ( + globalConfig, + contexts, + outputStream, + onComplete, + changedFilesPromise, + filter +) => { + const startRun = async () => { + if (!globalConfig.listTests) { + preRunMessagePrint(outputStream); + } + return (0, _runJest.default)({ + changedFilesPromise, + contexts, + failedTestsCache: undefined, + filter, + globalConfig, + onComplete, + outputStream, + startRun, + testWatcher: new (_jestWatcher().TestWatcher)({ + isWatchMode: false + }) + }); + }; + return startRun(); +}; diff --git a/node_modules/@jest/core/build/collectHandles.js b/node_modules/@jest/core/build/collectHandles.js new file mode 100644 index 0000000..60738d4 --- /dev/null +++ b/node_modules/@jest/core/build/collectHandles.js @@ -0,0 +1,266 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = collectHandles; +exports.formatHandleErrors = formatHandleErrors; +function asyncHooks() { + const data = _interopRequireWildcard(require('async_hooks')); + asyncHooks = function () { + return data; + }; + return data; +} +function _util() { + const data = require('util'); + _util = function () { + return data; + }; + return data; +} +function v8() { + const data = _interopRequireWildcard(require('v8')); + v8 = function () { + return data; + }; + return data; +} +function vm() { + const data = _interopRequireWildcard(require('vm')); + vm = function () { + return data; + }; + return data; +} +function _stripAnsi() { + const data = _interopRequireDefault(require('strip-ansi')); + _stripAnsi = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/ban-types-eventually */ + +function stackIsFromUser(stack) { + // Either the test file, or something required by it + if (stack.includes('Runtime.requireModule')) { + return true; + } + + // jest-jasmine it or describe call + if (stack.includes('asyncJestTest') || stack.includes('asyncJestLifecycle')) { + return true; + } + + // An async function call from within circus + if (stack.includes('callAsyncCircusFn')) { + // jest-circus it or describe call + return ( + stack.includes('_callCircusTest') || stack.includes('_callCircusHook') + ); + } + return false; +} +const alwaysActive = () => true; + +// @ts-expect-error: doesn't exist in v12 typings +const hasWeakRef = typeof WeakRef === 'function'; +const asyncSleep = (0, _util().promisify)(setTimeout); +let gcFunc = globalThis.gc; +function runGC() { + if (!gcFunc) { + v8().setFlagsFromString('--expose-gc'); + gcFunc = vm().runInNewContext('gc'); + v8().setFlagsFromString('--no-expose-gc'); + if (!gcFunc) { + throw new Error( + 'Cannot find `global.gc` function. Please run node with `--expose-gc` and report this issue in jest repo.' + ); + } + } + gcFunc(); +} + +// Inspired by https://github.com/mafintosh/why-is-node-running/blob/master/index.js +// Extracted as we want to format the result ourselves +function collectHandles() { + const activeHandles = new Map(); + const hook = asyncHooks().createHook({ + destroy(asyncId) { + activeHandles.delete(asyncId); + }, + init: function initHook(asyncId, type, triggerAsyncId, resource) { + // Skip resources that should not generally prevent the process from + // exiting, not last a meaningfully long time, or otherwise shouldn't be + // tracked. + if ( + type === 'PROMISE' || + type === 'TIMERWRAP' || + type === 'ELDHISTOGRAM' || + type === 'PerformanceObserver' || + type === 'RANDOMBYTESREQUEST' || + type === 'DNSCHANNEL' || + type === 'ZLIB' || + type === 'SIGNREQUEST' + ) { + return; + } + const error = new (_jestUtil().ErrorWithStack)(type, initHook, 100); + let fromUser = stackIsFromUser(error.stack || ''); + + // If the async resource was not directly created by user code, but was + // triggered by another async resource from user code, track it and use + // the original triggering resource's stack. + if (!fromUser) { + const triggeringHandle = activeHandles.get(triggerAsyncId); + if (triggeringHandle) { + fromUser = true; + error.stack = triggeringHandle.error.stack; + } + } + if (fromUser) { + let isActive; + + // Handle that supports hasRef + if ('hasRef' in resource) { + if (hasWeakRef) { + // @ts-expect-error: doesn't exist in v12 typings + const ref = new WeakRef(resource); + isActive = () => { + return ref.deref()?.hasRef() ?? false; + }; + } else { + isActive = resource.hasRef.bind(resource); + } + } else { + // Handle that doesn't support hasRef + isActive = alwaysActive; + } + activeHandles.set(asyncId, { + error, + isActive + }); + } + } + }); + hook.enable(); + return async () => { + // Wait briefly for any async resources that have been queued for + // destruction to actually be destroyed. + // For example, Node.js TCP Servers are not destroyed until *after* their + // `close` callback runs. If someone finishes a test from the `close` + // callback, we will not yet have seen the resource be destroyed here. + await asyncSleep(100); + if (activeHandles.size > 0) { + // For some special objects such as `TLSWRAP`. + // Ref: https://github.com/facebook/jest/issues/11665 + runGC(); + await asyncSleep(0); + } + hook.disable(); + + // Get errors for every async resource still referenced at this moment + const result = Array.from(activeHandles.values()) + .filter(({isActive}) => isActive()) + .map(({error}) => error); + activeHandles.clear(); + return result; + }; +} +function formatHandleErrors(errors, config) { + const stacks = new Set(); + return ( + errors + .map(err => + (0, _jestMessageUtil().formatExecError)( + err, + config, + { + noStackTrace: false + }, + undefined, + true + ) + ) + // E.g. timeouts might give multiple traces to the same line of code + // This hairy filtering tries to remove entries with duplicate stack traces + .filter(handle => { + const ansiFree = (0, _stripAnsi().default)(handle); + const match = ansiFree.match(/\s+at(.*)/); + if (!match || match.length < 2) { + return true; + } + const stack = ansiFree.substr(ansiFree.indexOf(match[1])).trim(); + if (stacks.has(stack)) { + return false; + } + stacks.add(stack); + return true; + }) + ); +} diff --git a/node_modules/@jest/core/build/getChangedFilesPromise.js b/node_modules/@jest/core/build/getChangedFilesPromise.js new file mode 100644 index 0000000..198d3bb --- /dev/null +++ b/node_modules/@jest/core/build/getChangedFilesPromise.js @@ -0,0 +1,65 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getChangedFilesPromise; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestChangedFiles() { + const data = require('jest-changed-files'); + _jestChangedFiles = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getChangedFilesPromise(globalConfig, configs) { + if (globalConfig.onlyChanged) { + const allRootsForAllProjects = configs.reduce((roots, config) => { + if (config.roots) { + roots.push(...config.roots); + } + return roots; + }, []); + return (0, _jestChangedFiles().getChangedFilesForRoots)( + allRootsForAllProjects, + { + changedSince: globalConfig.changedSince, + lastCommit: globalConfig.lastCommit, + withAncestor: globalConfig.changedFilesWithAncestor + } + ).catch(e => { + const message = (0, _jestMessageUtil().formatExecError)(e, configs[0], { + noStackTrace: true + }) + .split('\n') + .filter(line => !line.includes('Command failed:')) + .join('\n'); + console.error(_chalk().default.red(`\n\n${message}`)); + process.exit(1); + }); + } + return undefined; +} diff --git a/node_modules/@jest/core/build/getConfigsOfProjectsToRun.js b/node_modules/@jest/core/build/getConfigsOfProjectsToRun.js new file mode 100644 index 0000000..79005da --- /dev/null +++ b/node_modules/@jest/core/build/getConfigsOfProjectsToRun.js @@ -0,0 +1,40 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getConfigsOfProjectsToRun; +var _getProjectDisplayName = _interopRequireDefault( + require('./getProjectDisplayName') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getConfigsOfProjectsToRun(projectConfigs, opts) { + const projectFilter = createProjectFilter(opts); + return projectConfigs.filter(config => { + const name = (0, _getProjectDisplayName.default)(config); + return projectFilter(name); + }); +} +function createProjectFilter(opts) { + const {selectProjects, ignoreProjects} = opts; + const always = () => true; + const selected = selectProjects + ? name => name && selectProjects.includes(name) + : always; + const notIgnore = ignoreProjects + ? name => !(name && ignoreProjects.includes(name)) + : always; + function test(name) { + return selected(name) && notIgnore(name); + } + return test; +} diff --git a/node_modules/@jest/core/build/getNoTestFound.js b/node_modules/@jest/core/build/getNoTestFound.js new file mode 100644 index 0000000..788e98d --- /dev/null +++ b/node_modules/@jest/core/build/getNoTestFound.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getNoTestFound; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +var _pluralize = _interopRequireDefault(require('./pluralize')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getNoTestFound(testRunData, globalConfig, willExitWith0) { + const testFiles = testRunData.reduce( + (current, testRun) => current + (testRun.matches.total || 0), + 0 + ); + let dataMessage; + if (globalConfig.runTestsByPath) { + dataMessage = `Files: ${globalConfig.nonFlagArgs + .map(p => `"${p}"`) + .join(', ')}`; + } else { + dataMessage = `Pattern: ${_chalk().default.yellow( + globalConfig.testPathPattern + )} - 0 matches`; + } + if (willExitWith0) { + return ( + `${_chalk().default.bold('No tests found, exiting with code 0')}\n` + + `In ${_chalk().default.bold(globalConfig.rootDir)}` + + '\n' + + ` ${(0, _pluralize.default)('file', testFiles, 's')} checked across ${(0, + _pluralize.default)( + 'project', + testRunData.length, + 's' + )}. Run with \`--verbose\` for more details.` + + `\n${dataMessage}` + ); + } + return ( + `${_chalk().default.bold('No tests found, exiting with code 1')}\n` + + 'Run with `--passWithNoTests` to exit with code 0' + + '\n' + + `In ${_chalk().default.bold(globalConfig.rootDir)}` + + '\n' + + ` ${(0, _pluralize.default)('file', testFiles, 's')} checked across ${(0, + _pluralize.default)( + 'project', + testRunData.length, + 's' + )}. Run with \`--verbose\` for more details.` + + `\n${dataMessage}` + ); +} diff --git a/node_modules/@jest/core/build/getNoTestFoundFailed.js b/node_modules/@jest/core/build/getNoTestFoundFailed.js new file mode 100644 index 0000000..2367eef --- /dev/null +++ b/node_modules/@jest/core/build/getNoTestFoundFailed.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getNoTestFoundFailed; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getNoTestFoundFailed(globalConfig) { + let msg = _chalk().default.bold('No failed test found.'); + if (_jestUtil().isInteractive) { + msg += _chalk().default.dim( + `\n${ + globalConfig.watch + ? 'Press `f` to quit "only failed tests" mode.' + : 'Run Jest without `--onlyFailures` or with `--all` to run all tests.' + }` + ); + } + return msg; +} diff --git a/node_modules/@jest/core/build/getNoTestFoundPassWithNoTests.js b/node_modules/@jest/core/build/getNoTestFoundPassWithNoTests.js new file mode 100644 index 0000000..2aa188a --- /dev/null +++ b/node_modules/@jest/core/build/getNoTestFoundPassWithNoTests.js @@ -0,0 +1,26 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getNoTestFoundPassWithNoTests; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getNoTestFoundPassWithNoTests() { + return _chalk().default.bold('No tests found, exiting with code 0'); +} diff --git a/node_modules/@jest/core/build/getNoTestFoundRelatedToChangedFiles.js b/node_modules/@jest/core/build/getNoTestFoundRelatedToChangedFiles.js new file mode 100644 index 0000000..41e81f3 --- /dev/null +++ b/node_modules/@jest/core/build/getNoTestFoundRelatedToChangedFiles.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getNoTestFoundRelatedToChangedFiles; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getNoTestFoundRelatedToChangedFiles(globalConfig) { + const ref = globalConfig.changedSince + ? `"${globalConfig.changedSince}"` + : 'last commit'; + let msg = _chalk().default.bold( + `No tests found related to files changed since ${ref}.` + ); + if (_jestUtil().isInteractive) { + msg += _chalk().default.dim( + `\n${ + globalConfig.watch + ? 'Press `a` to run all tests, or run Jest with `--watchAll`.' + : 'Run Jest without `-o` or with `--all` to run all tests.' + }` + ); + } + return msg; +} diff --git a/node_modules/@jest/core/build/getNoTestFoundVerbose.js b/node_modules/@jest/core/build/getNoTestFoundVerbose.js new file mode 100644 index 0000000..8040783 --- /dev/null +++ b/node_modules/@jest/core/build/getNoTestFoundVerbose.js @@ -0,0 +1,85 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getNoTestFoundVerbose; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +var _pluralize = _interopRequireDefault(require('./pluralize')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getNoTestFoundVerbose(testRunData, globalConfig, willExitWith0) { + const individualResults = testRunData.map(testRun => { + const stats = testRun.matches.stats || {}; + const config = testRun.context.config; + const statsMessage = Object.keys(stats) + .map(key => { + if (key === 'roots' && config.roots.length === 1) { + return null; + } + const value = config[key]; + if (value) { + const valueAsString = Array.isArray(value) + ? value.join(', ') + : String(value); + const matches = (0, _pluralize.default)( + 'match', + stats[key] || 0, + 'es' + ); + return ` ${key}: ${_chalk().default.yellow( + valueAsString + )} - ${matches}`; + } + return null; + }) + .filter(line => line) + .join('\n'); + return testRun.matches.total + ? `In ${_chalk().default.bold(config.rootDir)}\n` + + ` ${(0, _pluralize.default)( + 'file', + testRun.matches.total || 0, + 's' + )} checked.\n${statsMessage}` + : `No files found in ${config.rootDir}.\n` + + "Make sure Jest's configuration does not exclude this directory." + + '\nTo set up Jest, make sure a package.json file exists.\n' + + 'Jest Documentation: ' + + 'https://jestjs.io/docs/configuration'; + }); + let dataMessage; + if (globalConfig.runTestsByPath) { + dataMessage = `Files: ${globalConfig.nonFlagArgs + .map(p => `"${p}"`) + .join(', ')}`; + } else { + dataMessage = `Pattern: ${_chalk().default.yellow( + globalConfig.testPathPattern + )} - 0 matches`; + } + if (willExitWith0) { + return `${_chalk().default.bold( + 'No tests found, exiting with code 0' + )}\n${individualResults.join('\n')}\n${dataMessage}`; + } + return ( + `${_chalk().default.bold('No tests found, exiting with code 1')}\n` + + 'Run with `--passWithNoTests` to exit with code 0' + + `\n${individualResults.join('\n')}\n${dataMessage}` + ); +} diff --git a/node_modules/@jest/core/build/getNoTestsFoundMessage.js b/node_modules/@jest/core/build/getNoTestsFoundMessage.js new file mode 100644 index 0000000..62b34f1 --- /dev/null +++ b/node_modules/@jest/core/build/getNoTestsFoundMessage.js @@ -0,0 +1,64 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getNoTestsFoundMessage; +var _getNoTestFound = _interopRequireDefault(require('./getNoTestFound')); +var _getNoTestFoundFailed = _interopRequireDefault( + require('./getNoTestFoundFailed') +); +var _getNoTestFoundPassWithNoTests = _interopRequireDefault( + require('./getNoTestFoundPassWithNoTests') +); +var _getNoTestFoundRelatedToChangedFiles = _interopRequireDefault( + require('./getNoTestFoundRelatedToChangedFiles') +); +var _getNoTestFoundVerbose = _interopRequireDefault( + require('./getNoTestFoundVerbose') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getNoTestsFoundMessage(testRunData, globalConfig) { + const exitWith0 = + globalConfig.passWithNoTests || + globalConfig.lastCommit || + globalConfig.onlyChanged; + if (globalConfig.onlyFailures) { + return { + exitWith0, + message: (0, _getNoTestFoundFailed.default)(globalConfig) + }; + } + if (globalConfig.onlyChanged) { + return { + exitWith0, + message: (0, _getNoTestFoundRelatedToChangedFiles.default)(globalConfig) + }; + } + if (globalConfig.passWithNoTests) { + return { + exitWith0, + message: (0, _getNoTestFoundPassWithNoTests.default)() + }; + } + return { + exitWith0, + message: + testRunData.length === 1 || globalConfig.verbose + ? (0, _getNoTestFoundVerbose.default)( + testRunData, + globalConfig, + exitWith0 + ) + : (0, _getNoTestFound.default)(testRunData, globalConfig, exitWith0) + }; +} diff --git a/node_modules/@jest/core/build/getProjectDisplayName.js b/node_modules/@jest/core/build/getProjectDisplayName.js new file mode 100644 index 0000000..e5d4e3e --- /dev/null +++ b/node_modules/@jest/core/build/getProjectDisplayName.js @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getProjectDisplayName; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getProjectDisplayName(projectConfig) { + return projectConfig.displayName?.name || undefined; +} diff --git a/node_modules/@jest/core/build/getProjectNamesMissingWarning.js b/node_modules/@jest/core/build/getProjectNamesMissingWarning.js new file mode 100644 index 0000000..233853d --- /dev/null +++ b/node_modules/@jest/core/build/getProjectNamesMissingWarning.js @@ -0,0 +1,49 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getProjectNamesMissingWarning; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +var _getProjectDisplayName = _interopRequireDefault( + require('./getProjectDisplayName') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getProjectNamesMissingWarning(projectConfigs, opts) { + const numberOfProjectsWithoutAName = projectConfigs.filter( + config => !(0, _getProjectDisplayName.default)(config) + ).length; + if (numberOfProjectsWithoutAName === 0) { + return undefined; + } + const args = []; + if (opts.selectProjects) { + args.push('--selectProjects'); + } + if (opts.ignoreProjects) { + args.push('--ignoreProjects'); + } + return _chalk().default.yellow( + `You provided values for ${args.join(' and ')} but ${ + numberOfProjectsWithoutAName === 1 + ? 'a project does not have a name' + : `${numberOfProjectsWithoutAName} projects do not have a name` + }.\n` + + 'Set displayName in the config of all projects in order to disable this warning.\n' + ); +} diff --git a/node_modules/@jest/core/build/getSelectProjectsMessage.js b/node_modules/@jest/core/build/getSelectProjectsMessage.js new file mode 100644 index 0000000..0b3c260 --- /dev/null +++ b/node_modules/@jest/core/build/getSelectProjectsMessage.js @@ -0,0 +1,71 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getSelectProjectsMessage; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +var _getProjectDisplayName = _interopRequireDefault( + require('./getProjectDisplayName') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getSelectProjectsMessage(projectConfigs, opts) { + if (projectConfigs.length === 0) { + return getNoSelectionWarning(opts); + } + return getProjectsRunningMessage(projectConfigs); +} +function getNoSelectionWarning(opts) { + if (opts.ignoreProjects && opts.selectProjects) { + return _chalk().default.yellow( + 'You provided values for --selectProjects and --ignoreProjects, but no projects were found matching the selection.\n' + + 'Are you ignoring all the selected projects?\n' + ); + } else if (opts.ignoreProjects) { + return _chalk().default.yellow( + 'You provided values for --ignoreProjects, but no projects were found matching the selection.\n' + + 'Are you ignoring all projects?\n' + ); + } else if (opts.selectProjects) { + return _chalk().default.yellow( + 'You provided values for --selectProjects but no projects were found matching the selection.\n' + ); + } else { + return _chalk().default.yellow('No projects were found.\n'); + } +} +function getProjectsRunningMessage(projectConfigs) { + if (projectConfigs.length === 1) { + const name = + (0, _getProjectDisplayName.default)(projectConfigs[0]) ?? + ''; + return `Running one project: ${_chalk().default.bold(name)}\n`; + } + const projectsList = projectConfigs + .map(getProjectNameListElement) + .sort() + .join('\n'); + return `Running ${projectConfigs.length} projects:\n${projectsList}\n`; +} +function getProjectNameListElement(projectConfig) { + const name = (0, _getProjectDisplayName.default)(projectConfig); + const elementContent = name + ? _chalk().default.bold(name) + : ''; + return `- ${elementContent}`; +} diff --git a/node_modules/@jest/core/build/index.d.ts b/node_modules/@jest/core/build/index.d.ts new file mode 100644 index 0000000..937dad6 --- /dev/null +++ b/node_modules/@jest/core/build/index.d.ts @@ -0,0 +1,118 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import {AggregatedResult} from '@jest/test-result'; +import {BaseReporter} from '@jest/reporters'; +import type {ChangedFiles} from 'jest-changed-files'; +import type {Config} from '@jest/types'; +import {Reporter} from '@jest/reporters'; +import {ReporterContext} from '@jest/reporters'; +import {Test} from '@jest/test-result'; +import type {TestContext} from '@jest/test-result'; +import type {TestRunnerContext} from 'jest-runner'; +import type {TestWatcher} from 'jest-watcher'; + +export declare function createTestScheduler( + globalConfig: Config.GlobalConfig, + context: TestSchedulerContext, +): Promise; + +declare type Filter = (testPaths: Array) => Promise<{ + filtered: Array; +}>; + +declare type FilterResult = { + test: string; + message: string; +}; + +export declare function getVersion(): string; + +declare type ReporterConstructor = new ( + globalConfig: Config.GlobalConfig, + reporterConfig: Record, + reporterContext: ReporterContext, +) => BaseReporter; + +export declare function runCLI( + argv: Config.Argv, + projects: Array, +): Promise<{ + results: AggregatedResult; + globalConfig: Config.GlobalConfig; +}>; + +declare type SearchResult = { + noSCM?: boolean; + stats?: Stats; + collectCoverageFrom?: Set; + tests: Array; + total?: number; +}; + +export declare class SearchSource { + private readonly _context; + private _dependencyResolver; + private readonly _testPathCases; + constructor(context: TestContext); + private _getOrBuildDependencyResolver; + private _filterTestPathsWithStats; + private _getAllTestPaths; + isTestFilePath(path: string): boolean; + findMatchingTests(testPathPattern: string): SearchResult; + findRelatedTests( + allPaths: Set, + collectCoverage: boolean, + ): Promise; + findTestsByPaths(paths: Array): SearchResult; + findRelatedTestsFromPattern( + paths: Array, + collectCoverage: boolean, + ): Promise; + findTestRelatedToChangedFiles( + changedFilesInfo: ChangedFiles, + collectCoverage: boolean, + ): Promise; + private _getTestPaths; + filterPathsWin32(paths: Array): Array; + getTestPaths( + globalConfig: Config.GlobalConfig, + changedFiles?: ChangedFiles, + filter?: Filter, + ): Promise; + findRelatedSourcesFromTestsInChangedFiles( + changedFilesInfo: ChangedFiles, + ): Promise>; +} + +declare type Stats = { + roots: number; + testMatch: number; + testPathIgnorePatterns: number; + testRegex: number; + testPathPattern?: number; +}; + +declare class TestScheduler { + private readonly _context; + private readonly _dispatcher; + private readonly _globalConfig; + constructor(globalConfig: Config.GlobalConfig, context: TestSchedulerContext); + addReporter(reporter: Reporter): void; + removeReporter(reporterConstructor: ReporterConstructor): void; + scheduleTests( + tests: Array, + watcher: TestWatcher, + ): Promise; + private _partitionTests; + _setupReporters(): Promise; + private _addCustomReporter; + private _bailIfNeeded; +} + +declare type TestSchedulerContext = ReporterContext & TestRunnerContext; + +export {}; diff --git a/node_modules/@jest/core/build/index.js b/node_modules/@jest/core/build/index.js new file mode 100644 index 0000000..e6a0fe5 --- /dev/null +++ b/node_modules/@jest/core/build/index.js @@ -0,0 +1,36 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'SearchSource', { + enumerable: true, + get: function () { + return _SearchSource.default; + } +}); +Object.defineProperty(exports, 'createTestScheduler', { + enumerable: true, + get: function () { + return _TestScheduler.createTestScheduler; + } +}); +Object.defineProperty(exports, 'getVersion', { + enumerable: true, + get: function () { + return _version.default; + } +}); +Object.defineProperty(exports, 'runCLI', { + enumerable: true, + get: function () { + return _cli.runCLI; + } +}); +var _SearchSource = _interopRequireDefault(require('./SearchSource')); +var _TestScheduler = require('./TestScheduler'); +var _cli = require('./cli'); +var _version = _interopRequireDefault(require('./version')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} diff --git a/node_modules/@jest/core/build/lib/activeFiltersMessage.js b/node_modules/@jest/core/build/lib/activeFiltersMessage.js new file mode 100644 index 0000000..f17f30b --- /dev/null +++ b/node_modules/@jest/core/build/lib/activeFiltersMessage.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const activeFilters = (globalConfig, delimiter = '\n') => { + const {testNamePattern, testPathPattern} = globalConfig; + if (testNamePattern || testPathPattern) { + const filters = [ + testPathPattern + ? _chalk().default.dim('filename ') + + _chalk().default.yellow(`/${testPathPattern}/`) + : null, + testNamePattern + ? _chalk().default.dim('test name ') + + _chalk().default.yellow(`/${testNamePattern}/`) + : null + ] + .filter(f => f) + .join(', '); + const messages = [ + `\n${_chalk().default.bold('Active Filters: ')}${filters}` + ]; + return messages.filter(message => !!message).join(delimiter); + } + return ''; +}; +var _default = activeFilters; +exports.default = _default; diff --git a/node_modules/@jest/core/build/lib/createContext.js b/node_modules/@jest/core/build/lib/createContext.js new file mode 100644 index 0000000..1992b80 --- /dev/null +++ b/node_modules/@jest/core/build/lib/createContext.js @@ -0,0 +1,31 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = createContext; +function _jestRuntime() { + const data = _interopRequireDefault(require('jest-runtime')); + _jestRuntime = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function createContext(config, {hasteFS, moduleMap}) { + return { + config, + hasteFS, + moduleMap, + resolver: _jestRuntime().default.createResolver(config, moduleMap) + }; +} diff --git a/node_modules/@jest/core/build/lib/handleDeprecationWarnings.js b/node_modules/@jest/core/build/lib/handleDeprecationWarnings.js new file mode 100644 index 0000000..a883224 --- /dev/null +++ b/node_modules/@jest/core/build/lib/handleDeprecationWarnings.js @@ -0,0 +1,65 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = handleDeprecationWarnings; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function handleDeprecationWarnings(pipe, stdin = process.stdin) { + return new Promise((resolve, reject) => { + if (typeof stdin.setRawMode === 'function') { + const messages = [ + _chalk().default.red('There are deprecation warnings.\n'), + `${_chalk().default.dim(' \u203A Press ')}Enter${_chalk().default.dim( + ' to continue.' + )}`, + `${_chalk().default.dim(' \u203A Press ')}Esc${_chalk().default.dim( + ' to exit.' + )}` + ]; + pipe.write(messages.join('\n')); + stdin.setRawMode(true); + stdin.resume(); + stdin.setEncoding('utf8'); + // this is a string since we set encoding above + stdin.on('data', key => { + if (key === _jestWatcher().KEYS.ENTER) { + resolve(); + } else if ( + [ + _jestWatcher().KEYS.ESCAPE, + _jestWatcher().KEYS.CONTROL_C, + _jestWatcher().KEYS.CONTROL_D + ].indexOf(key) !== -1 + ) { + reject(); + } + }); + } else { + resolve(); + } + }); +} diff --git a/node_modules/@jest/core/build/lib/isValidPath.js b/node_modules/@jest/core/build/lib/isValidPath.js new file mode 100644 index 0000000..ea109f7 --- /dev/null +++ b/node_modules/@jest/core/build/lib/isValidPath.js @@ -0,0 +1,26 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = isValidPath; +function _jestSnapshot() { + const data = require('jest-snapshot'); + _jestSnapshot = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function isValidPath(globalConfig, filePath) { + return ( + !filePath.includes(globalConfig.coverageDirectory) && + !(0, _jestSnapshot().isSnapshotPath)(filePath) + ); +} diff --git a/node_modules/@jest/core/build/lib/logDebugMessages.js b/node_modules/@jest/core/build/lib/logDebugMessages.js new file mode 100644 index 0000000..1e647ac --- /dev/null +++ b/node_modules/@jest/core/build/lib/logDebugMessages.js @@ -0,0 +1,24 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = logDebugMessages; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const VERSION = require('../../package.json').version; + +// if the output here changes, update `getConfig` in e2e/runJest.ts +function logDebugMessages(globalConfig, configs, outputStream) { + const output = { + configs, + globalConfig, + version: VERSION + }; + outputStream.write(`${JSON.stringify(output, null, ' ')}\n`); +} diff --git a/node_modules/@jest/core/build/lib/updateGlobalConfig.js b/node_modules/@jest/core/build/lib/updateGlobalConfig.js new file mode 100644 index 0000000..11d933f --- /dev/null +++ b/node_modules/@jest/core/build/lib/updateGlobalConfig.js @@ -0,0 +1,95 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = updateGlobalConfig; +function _jestRegexUtil() { + const data = require('jest-regex-util'); + _jestRegexUtil = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function updateGlobalConfig(globalConfig, options = {}) { + const newConfig = { + ...globalConfig + }; + if (options.mode === 'watch') { + newConfig.watch = true; + newConfig.watchAll = false; + } else if (options.mode === 'watchAll') { + newConfig.watch = false; + newConfig.watchAll = true; + } + if (options.testNamePattern !== undefined) { + newConfig.testNamePattern = options.testNamePattern || ''; + } + if (options.testPathPattern !== undefined) { + newConfig.testPathPattern = + (0, _jestRegexUtil().replacePathSepForRegex)(options.testPathPattern) || + ''; + } + newConfig.onlyChanged = + !newConfig.watchAll && + !newConfig.testNamePattern && + !newConfig.testPathPattern; + if (typeof options.bail === 'boolean') { + newConfig.bail = options.bail ? 1 : 0; + } else if (options.bail !== undefined) { + newConfig.bail = options.bail; + } + if (options.changedSince !== undefined) { + newConfig.changedSince = options.changedSince; + } + if (options.collectCoverage !== undefined) { + newConfig.collectCoverage = options.collectCoverage || false; + } + if (options.collectCoverageFrom !== undefined) { + newConfig.collectCoverageFrom = options.collectCoverageFrom; + } + if (options.coverageDirectory !== undefined) { + newConfig.coverageDirectory = options.coverageDirectory; + } + if (options.coverageReporters !== undefined) { + newConfig.coverageReporters = options.coverageReporters; + } + if (options.findRelatedTests !== undefined) { + newConfig.findRelatedTests = options.findRelatedTests; + } + if (options.nonFlagArgs !== undefined) { + newConfig.nonFlagArgs = options.nonFlagArgs; + } + if (options.noSCM) { + newConfig.noSCM = true; + } + if (options.notify !== undefined) { + newConfig.notify = options.notify || false; + } + if (options.notifyMode !== undefined) { + newConfig.notifyMode = options.notifyMode; + } + if (options.onlyFailures !== undefined) { + newConfig.onlyFailures = options.onlyFailures || false; + } + if (options.passWithNoTests !== undefined) { + newConfig.passWithNoTests = true; + } + if (options.reporters !== undefined) { + newConfig.reporters = options.reporters; + } + if (options.updateSnapshot !== undefined) { + newConfig.updateSnapshot = options.updateSnapshot; + } + if (options.verbose !== undefined) { + newConfig.verbose = options.verbose || false; + } + return Object.freeze(newConfig); +} diff --git a/node_modules/@jest/core/build/lib/watchPluginsHelpers.js b/node_modules/@jest/core/build/lib/watchPluginsHelpers.js new file mode 100644 index 0000000..66386b7 --- /dev/null +++ b/node_modules/@jest/core/build/lib/watchPluginsHelpers.js @@ -0,0 +1,52 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getSortedUsageRows = exports.filterInteractivePlugins = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const filterInteractivePlugins = (watchPlugins, globalConfig) => { + const usageInfos = watchPlugins.map( + p => p.getUsageInfo && p.getUsageInfo(globalConfig) + ); + return watchPlugins.filter((_plugin, i) => { + const usageInfo = usageInfos[i]; + if (usageInfo) { + const {key} = usageInfo; + return !usageInfos.slice(i + 1).some(u => !!u && key === u.key); + } + return false; + }); +}; +exports.filterInteractivePlugins = filterInteractivePlugins; +function notEmpty(value) { + return value != null; +} +const getSortedUsageRows = (watchPlugins, globalConfig) => + filterInteractivePlugins(watchPlugins, globalConfig) + .sort((a, b) => { + if (a.isInternal && b.isInternal) { + // internal plugins in the order we specify them + return 0; + } + if (a.isInternal !== b.isInternal) { + // external plugins afterwards + return a.isInternal ? -1 : 1; + } + const usageInfoA = a.getUsageInfo && a.getUsageInfo(globalConfig); + const usageInfoB = b.getUsageInfo && b.getUsageInfo(globalConfig); + if (usageInfoA && usageInfoB) { + // external plugins in alphabetical order + return usageInfoA.key.localeCompare(usageInfoB.key); + } + return 0; + }) + .map(p => p.getUsageInfo && p.getUsageInfo(globalConfig)) + .filter(notEmpty); +exports.getSortedUsageRows = getSortedUsageRows; diff --git a/node_modules/@jest/core/build/plugins/FailedTestsInteractive.js b/node_modules/@jest/core/build/plugins/FailedTestsInteractive.js new file mode 100644 index 0000000..b567c60 --- /dev/null +++ b/node_modules/@jest/core/build/plugins/FailedTestsInteractive.js @@ -0,0 +1,96 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +var _FailedTestsInteractiveMode = _interopRequireDefault( + require('../FailedTestsInteractiveMode') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class FailedTestsInteractivePlugin extends _jestWatcher().BaseWatchPlugin { + _failedTestAssertions; + _manager = new _FailedTestsInteractiveMode.default(this._stdout); + apply(hooks) { + hooks.onTestRunComplete(results => { + this._failedTestAssertions = this.getFailedTestAssertions(results); + if (this._manager.isActive()) this._manager.updateWithResults(results); + }); + } + getUsageInfo() { + if (this._failedTestAssertions?.length) { + return { + key: 'i', + prompt: 'run failing tests interactively' + }; + } + return null; + } + onKey(key) { + if (this._manager.isActive()) { + this._manager.put(key); + } + } + run(_, updateConfigAndRun) { + return new Promise(resolve => { + if ( + !this._failedTestAssertions || + this._failedTestAssertions.length === 0 + ) { + resolve(); + return; + } + this._manager.run(this._failedTestAssertions, failure => { + updateConfigAndRun({ + mode: 'watch', + testNamePattern: failure ? `^${failure.fullName}$` : '', + testPathPattern: failure?.path || '' + }); + if (!this._manager.isActive()) { + resolve(); + } + }); + }); + } + getFailedTestAssertions(results) { + const failedTestPaths = []; + if ( + // skip if no failed tests + results.numFailedTests === 0 || + // skip if missing test results + !results.testResults || + // skip if unmatched snapshots are present + results.snapshot.unmatched + ) { + return failedTestPaths; + } + results.testResults.forEach(testResult => { + testResult.testResults.forEach(result => { + if (result.status === 'failed') { + failedTestPaths.push({ + fullName: result.fullName, + path: testResult.testFilePath + }); + } + }); + }); + return failedTestPaths; + } +} +exports.default = FailedTestsInteractivePlugin; diff --git a/node_modules/@jest/core/build/plugins/Quit.js b/node_modules/@jest/core/build/plugins/Quit.js new file mode 100644 index 0000000..d91277b --- /dev/null +++ b/node_modules/@jest/core/build/plugins/Quit.js @@ -0,0 +1,42 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class QuitPlugin extends _jestWatcher().BaseWatchPlugin { + isInternal; + constructor(options) { + super(options); + this.isInternal = true; + } + async run() { + if (typeof this._stdin.setRawMode === 'function') { + this._stdin.setRawMode(false); + } + this._stdout.write('\n'); + process.exit(0); + } + getUsageInfo() { + return { + key: 'q', + prompt: 'quit watch mode' + }; + } +} +var _default = QuitPlugin; +exports.default = _default; diff --git a/node_modules/@jest/core/build/plugins/TestNamePattern.js b/node_modules/@jest/core/build/plugins/TestNamePattern.js new file mode 100644 index 0000000..c9d3c83 --- /dev/null +++ b/node_modules/@jest/core/build/plugins/TestNamePattern.js @@ -0,0 +1,70 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +var _TestNamePatternPrompt = _interopRequireDefault( + require('../TestNamePatternPrompt') +); +var _activeFiltersMessage = _interopRequireDefault( + require('../lib/activeFiltersMessage') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class TestNamePatternPlugin extends _jestWatcher().BaseWatchPlugin { + _prompt; + isInternal; + constructor(options) { + super(options); + this._prompt = new (_jestWatcher().Prompt)(); + this.isInternal = true; + } + getUsageInfo() { + return { + key: 't', + prompt: 'filter by a test name regex pattern' + }; + } + onKey(key) { + this._prompt.put(key); + } + run(globalConfig, updateConfigAndRun) { + return new Promise((res, rej) => { + const testNamePatternPrompt = new _TestNamePatternPrompt.default( + this._stdout, + this._prompt + ); + testNamePatternPrompt.run( + value => { + updateConfigAndRun({ + mode: 'watch', + testNamePattern: value + }); + res(); + }, + rej, + { + header: (0, _activeFiltersMessage.default)(globalConfig) + } + ); + }); + } +} +var _default = TestNamePatternPlugin; +exports.default = _default; diff --git a/node_modules/@jest/core/build/plugins/TestPathPattern.js b/node_modules/@jest/core/build/plugins/TestPathPattern.js new file mode 100644 index 0000000..a454ee7 --- /dev/null +++ b/node_modules/@jest/core/build/plugins/TestPathPattern.js @@ -0,0 +1,70 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +var _TestPathPatternPrompt = _interopRequireDefault( + require('../TestPathPatternPrompt') +); +var _activeFiltersMessage = _interopRequireDefault( + require('../lib/activeFiltersMessage') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class TestPathPatternPlugin extends _jestWatcher().BaseWatchPlugin { + _prompt; + isInternal; + constructor(options) { + super(options); + this._prompt = new (_jestWatcher().Prompt)(); + this.isInternal = true; + } + getUsageInfo() { + return { + key: 'p', + prompt: 'filter by a filename regex pattern' + }; + } + onKey(key) { + this._prompt.put(key); + } + run(globalConfig, updateConfigAndRun) { + return new Promise((res, rej) => { + const testPathPatternPrompt = new _TestPathPatternPrompt.default( + this._stdout, + this._prompt + ); + testPathPatternPrompt.run( + value => { + updateConfigAndRun({ + mode: 'watch', + testPathPattern: value + }); + res(); + }, + rej, + { + header: (0, _activeFiltersMessage.default)(globalConfig) + } + ); + }); + } +} +var _default = TestPathPatternPlugin; +exports.default = _default; diff --git a/node_modules/@jest/core/build/plugins/UpdateSnapshots.js b/node_modules/@jest/core/build/plugins/UpdateSnapshots.js new file mode 100644 index 0000000..e8e0e11 --- /dev/null +++ b/node_modules/@jest/core/build/plugins/UpdateSnapshots.js @@ -0,0 +1,51 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class UpdateSnapshotsPlugin extends _jestWatcher().BaseWatchPlugin { + _hasSnapshotFailure; + isInternal; + constructor(options) { + super(options); + this.isInternal = true; + this._hasSnapshotFailure = false; + } + run(_globalConfig, updateConfigAndRun) { + updateConfigAndRun({ + updateSnapshot: 'all' + }); + return Promise.resolve(false); + } + apply(hooks) { + hooks.onTestRunComplete(results => { + this._hasSnapshotFailure = results.snapshot.failure; + }); + } + getUsageInfo() { + if (this._hasSnapshotFailure) { + return { + key: 'u', + prompt: 'update failing snapshots' + }; + } + return null; + } +} +var _default = UpdateSnapshotsPlugin; +exports.default = _default; diff --git a/node_modules/@jest/core/build/plugins/UpdateSnapshotsInteractive.js b/node_modules/@jest/core/build/plugins/UpdateSnapshotsInteractive.js new file mode 100644 index 0000000..1236070 --- /dev/null +++ b/node_modules/@jest/core/build/plugins/UpdateSnapshotsInteractive.js @@ -0,0 +1,99 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +var _SnapshotInteractiveMode = _interopRequireDefault( + require('../SnapshotInteractiveMode') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/ban-types-eventually */ + +class UpdateSnapshotInteractivePlugin extends _jestWatcher().BaseWatchPlugin { + _snapshotInteractiveMode = new _SnapshotInteractiveMode.default(this._stdout); + _failedSnapshotTestAssertions = []; + isInternal = true; + getFailedSnapshotTestAssertions(testResults) { + const failedTestPaths = []; + if (testResults.numFailedTests === 0 || !testResults.testResults) { + return failedTestPaths; + } + testResults.testResults.forEach(testResult => { + if (testResult.snapshot && testResult.snapshot.unmatched) { + testResult.testResults.forEach(result => { + if (result.status === 'failed') { + failedTestPaths.push({ + fullName: result.fullName, + path: testResult.testFilePath + }); + } + }); + } + }); + return failedTestPaths; + } + apply(hooks) { + hooks.onTestRunComplete(results => { + this._failedSnapshotTestAssertions = + this.getFailedSnapshotTestAssertions(results); + if (this._snapshotInteractiveMode.isActive()) { + this._snapshotInteractiveMode.updateWithResults(results); + } + }); + } + onKey(key) { + if (this._snapshotInteractiveMode.isActive()) { + this._snapshotInteractiveMode.put(key); + } + } + run(_globalConfig, updateConfigAndRun) { + if (this._failedSnapshotTestAssertions.length) { + return new Promise(res => { + this._snapshotInteractiveMode.run( + this._failedSnapshotTestAssertions, + (assertion, shouldUpdateSnapshot) => { + updateConfigAndRun({ + mode: 'watch', + testNamePattern: assertion ? `^${assertion.fullName}$` : '', + testPathPattern: assertion ? assertion.path : '', + updateSnapshot: shouldUpdateSnapshot ? 'all' : 'none' + }); + if (!this._snapshotInteractiveMode.isActive()) { + res(); + } + } + ); + }); + } else { + return Promise.resolve(); + } + } + getUsageInfo() { + if (this._failedSnapshotTestAssertions?.length > 0) { + return { + key: 'i', + prompt: 'update failing snapshots interactively' + }; + } + return null; + } +} +var _default = UpdateSnapshotInteractivePlugin; +exports.default = _default; diff --git a/node_modules/@jest/core/build/pluralize.js b/node_modules/@jest/core/build/pluralize.js new file mode 100644 index 0000000..3543eb7 --- /dev/null +++ b/node_modules/@jest/core/build/pluralize.js @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = pluralize; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function pluralize(word, count, ending) { + return `${count} ${word}${count === 1 ? '' : ending}`; +} diff --git a/node_modules/@jest/core/build/runGlobalHook.js b/node_modules/@jest/core/build/runGlobalHook.js new file mode 100644 index 0000000..d12fa74 --- /dev/null +++ b/node_modules/@jest/core/build/runGlobalHook.js @@ -0,0 +1,126 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = runGlobalHook; +function util() { + const data = _interopRequireWildcard(require('util')); + util = function () { + return data; + }; + return data; +} +function _transform() { + const data = require('@jest/transform'); + _transform = function () { + return data; + }; + return data; +} +function _prettyFormat() { + const data = _interopRequireDefault(require('pretty-format')); + _prettyFormat = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +async function runGlobalHook({allTests, globalConfig, moduleName}) { + const globalModulePaths = new Set( + allTests.map(test => test.context.config[moduleName]) + ); + if (globalConfig[moduleName]) { + globalModulePaths.add(globalConfig[moduleName]); + } + if (globalModulePaths.size > 0) { + for (const modulePath of globalModulePaths) { + if (!modulePath) { + continue; + } + const correctConfig = allTests.find( + t => t.context.config[moduleName] === modulePath + ); + const projectConfig = correctConfig + ? correctConfig.context.config + : // Fallback to first config + allTests[0].context.config; + const transformer = await (0, _transform().createScriptTransformer)( + projectConfig + ); + try { + await transformer.requireAndTranspileModule( + modulePath, + async globalModule => { + if (typeof globalModule !== 'function') { + throw new TypeError( + `${moduleName} file must export a function at ${modulePath}` + ); + } + await globalModule(globalConfig, projectConfig); + } + ); + } catch (error) { + if (util().types.isNativeError(error)) { + error.message = `Jest: Got error running ${moduleName} - ${modulePath}, reason: ${error.message}`; + throw error; + } + throw new Error( + `Jest: Got error running ${moduleName} - ${modulePath}, reason: ${(0, + _prettyFormat().default)(error, { + maxDepth: 3 + })}` + ); + } + } + } +} diff --git a/node_modules/@jest/core/build/runJest.js b/node_modules/@jest/core/build/runJest.js new file mode 100644 index 0000000..14117a9 --- /dev/null +++ b/node_modules/@jest/core/build/runJest.js @@ -0,0 +1,366 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = runJest; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _exit() { + const data = _interopRequireDefault(require('exit')); + _exit = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _console() { + const data = require('@jest/console'); + _console = function () { + return data; + }; + return data; +} +function _testResult() { + const data = require('@jest/test-result'); + _testResult = function () { + return data; + }; + return data; +} +function _jestResolve() { + const data = _interopRequireDefault(require('jest-resolve')); + _jestResolve = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +var _SearchSource = _interopRequireDefault(require('./SearchSource')); +var _TestScheduler = require('./TestScheduler'); +var _collectHandles = _interopRequireDefault(require('./collectHandles')); +var _getNoTestsFoundMessage = _interopRequireDefault( + require('./getNoTestsFoundMessage') +); +var _runGlobalHook = _interopRequireDefault(require('./runGlobalHook')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const getTestPaths = async ( + globalConfig, + source, + outputStream, + changedFiles, + jestHooks, + filter +) => { + const data = await source.getTestPaths(globalConfig, changedFiles, filter); + if (!data.tests.length && globalConfig.onlyChanged && data.noSCM) { + new (_console().CustomConsole)(outputStream, outputStream).log( + 'Jest can only find uncommitted changed files in a git or hg ' + + 'repository. If you make your project a git or hg ' + + 'repository (`git init` or `hg init`), Jest will be able ' + + 'to only run tests related to files changed since the last ' + + 'commit.' + ); + } + const shouldTestArray = await Promise.all( + data.tests.map(test => + jestHooks.shouldRunTestSuite({ + config: test.context.config, + duration: test.duration, + testPath: test.path + }) + ) + ); + const filteredTests = data.tests.filter((_test, i) => shouldTestArray[i]); + return { + ...data, + allTests: filteredTests.length, + tests: filteredTests + }; +}; +const processResults = async (runResults, options) => { + const { + outputFile, + json: isJSON, + onComplete, + outputStream, + testResultsProcessor, + collectHandles + } = options; + if (collectHandles) { + runResults.openHandles = await collectHandles(); + } else { + runResults.openHandles = []; + } + if (testResultsProcessor) { + const processor = await (0, _jestUtil().requireOrImportModule)( + testResultsProcessor + ); + runResults = await processor(runResults); + } + if (isJSON) { + if (outputFile) { + const cwd = (0, _jestUtil().tryRealpath)(process.cwd()); + const filePath = path().resolve(cwd, outputFile); + fs().writeFileSync( + filePath, + JSON.stringify((0, _testResult().formatTestResults)(runResults)) + ); + outputStream.write( + `Test results written to: ${path().relative(cwd, filePath)}\n` + ); + } else { + process.stdout.write( + JSON.stringify((0, _testResult().formatTestResults)(runResults)) + ); + } + } + onComplete?.(runResults); +}; +const testSchedulerContext = { + firstRun: true, + previousSuccess: true +}; +async function runJest({ + contexts, + globalConfig, + outputStream, + testWatcher, + jestHooks = new (_jestWatcher().JestHook)().getEmitter(), + startRun, + changedFilesPromise, + onComplete, + failedTestsCache, + filter +}) { + // Clear cache for required modules - there might be different resolutions + // from Jest's config loading to running the tests + _jestResolve().default.clearDefaultResolverCache(); + const Sequencer = await (0, _jestUtil().requireOrImportModule)( + globalConfig.testSequencer + ); + const sequencer = new Sequencer(); + let allTests = []; + if (changedFilesPromise && globalConfig.watch) { + const {repos} = await changedFilesPromise; + const noSCM = Object.keys(repos).every(scm => repos[scm].size === 0); + if (noSCM) { + process.stderr.write( + `\n${_chalk().default.bold( + '--watch' + )} is not supported without git/hg, please use --watchAll\n` + ); + (0, _exit().default)(1); + } + } + const searchSources = contexts.map( + context => new _SearchSource.default(context) + ); + const testRunData = await Promise.all( + contexts.map(async (context, index) => { + const searchSource = searchSources[index]; + const matches = await getTestPaths( + globalConfig, + searchSource, + outputStream, + changedFilesPromise && (await changedFilesPromise), + jestHooks, + filter + ); + allTests = allTests.concat(matches.tests); + return { + context, + matches + }; + }) + ); + if (globalConfig.shard) { + if (typeof sequencer.shard !== 'function') { + throw new Error( + `Shard ${globalConfig.shard.shardIndex}/${globalConfig.shard.shardCount} requested, but test sequencer ${Sequencer.name} in ${globalConfig.testSequencer} has no shard method.` + ); + } + allTests = await sequencer.shard(allTests, globalConfig.shard); + } + allTests = await sequencer.sort(allTests); + if (globalConfig.listTests) { + const testsPaths = Array.from(new Set(allTests.map(test => test.path))); + /* eslint-disable no-console */ + if (globalConfig.json) { + console.log(JSON.stringify(testsPaths)); + } else { + console.log(testsPaths.join('\n')); + } + /* eslint-enable */ + + onComplete && + onComplete((0, _testResult().makeEmptyAggregatedTestResult)()); + return; + } + if (globalConfig.onlyFailures) { + if (failedTestsCache) { + allTests = failedTestsCache.filterTests(allTests); + } else { + allTests = await sequencer.allFailedTests(allTests); + } + } + const hasTests = allTests.length > 0; + if (!hasTests) { + const {exitWith0, message: noTestsFoundMessage} = (0, + _getNoTestsFoundMessage.default)(testRunData, globalConfig); + if (exitWith0) { + new (_console().CustomConsole)(outputStream, outputStream).log( + noTestsFoundMessage + ); + } else { + new (_console().CustomConsole)(outputStream, outputStream).error( + noTestsFoundMessage + ); + (0, _exit().default)(1); + } + } else if ( + allTests.length === 1 && + globalConfig.silent !== true && + globalConfig.verbose !== false + ) { + const newConfig = { + ...globalConfig, + verbose: true + }; + globalConfig = Object.freeze(newConfig); + } + let collectHandles; + if (globalConfig.detectOpenHandles) { + collectHandles = (0, _collectHandles.default)(); + } + if (hasTests) { + await (0, _runGlobalHook.default)({ + allTests, + globalConfig, + moduleName: 'globalSetup' + }); + } + if (changedFilesPromise) { + const changedFilesInfo = await changedFilesPromise; + if (changedFilesInfo.changedFiles) { + testSchedulerContext.changedFiles = changedFilesInfo.changedFiles; + const sourcesRelatedToTestsInChangedFilesArray = ( + await Promise.all( + contexts.map(async (_, index) => { + const searchSource = searchSources[index]; + return searchSource.findRelatedSourcesFromTestsInChangedFiles( + changedFilesInfo + ); + }) + ) + ).reduce((total, paths) => total.concat(paths), []); + testSchedulerContext.sourcesRelatedToTestsInChangedFiles = new Set( + sourcesRelatedToTestsInChangedFilesArray + ); + } + } + const scheduler = await (0, _TestScheduler.createTestScheduler)( + globalConfig, + { + startRun, + ...testSchedulerContext + } + ); + const results = await scheduler.scheduleTests(allTests, testWatcher); + sequencer.cacheResults(allTests, results); + if (hasTests) { + await (0, _runGlobalHook.default)({ + allTests, + globalConfig, + moduleName: 'globalTeardown' + }); + } + await processResults(results, { + collectHandles, + json: globalConfig.json, + onComplete, + outputFile: globalConfig.outputFile, + outputStream, + testResultsProcessor: globalConfig.testResultsProcessor + }); +} diff --git a/node_modules/@jest/core/build/testSchedulerHelper.js b/node_modules/@jest/core/build/testSchedulerHelper.js new file mode 100644 index 0000000..562749b --- /dev/null +++ b/node_modules/@jest/core/build/testSchedulerHelper.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.shouldRunInBand = shouldRunInBand; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const SLOW_TEST_TIME = 1000; +function shouldRunInBand( + tests, + timings, + {detectOpenHandles, maxWorkers, watch, watchAll} +) { + // detectOpenHandles makes no sense without runInBand, because it cannot detect leaks in workers + if (detectOpenHandles) { + return true; + } + + /* + * Run in band if we only have one test or one worker available, unless we + * are using the watch mode, in which case the TTY has to be responsive and + * we cannot schedule anything in the main thread. Same logic applies to + * watchAll. + * Also, if we are confident from previous runs that the tests will finish + * quickly we also run in band to reduce the overhead of spawning workers. + * Finally, the user can provide the runInBand argument in the CLI to + * force running in band. + * https://github.com/facebook/jest/blob/700e0dadb85f5dc8ff5dac6c7e98956690049734/packages/jest-config/src/getMaxWorkers.js#L14-L17 + */ + const isWatchMode = watch || watchAll; + const areFastTests = timings.every(timing => timing < SLOW_TEST_TIME); + const oneWorkerOrLess = maxWorkers <= 1; + const oneTestOrLess = tests.length <= 1; + if (isWatchMode) { + return oneWorkerOrLess || (oneTestOrLess && areFastTests); + } + return ( + oneWorkerOrLess || + oneTestOrLess || + (tests.length <= 20 && timings.length > 0 && areFastTests) + ); +} diff --git a/node_modules/@jest/core/build/types.js b/node_modules/@jest/core/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/core/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/core/build/version.js b/node_modules/@jest/core/build/version.js new file mode 100644 index 0000000..6377040 --- /dev/null +++ b/node_modules/@jest/core/build/version.js @@ -0,0 +1,18 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getVersion; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Cannot be `import` as it's not under TS root dir +const {version: VERSION} = require('../package.json'); +function getVersion() { + return VERSION; +} diff --git a/node_modules/@jest/core/build/watch.js b/node_modules/@jest/core/build/watch.js new file mode 100644 index 0000000..80b1647 --- /dev/null +++ b/node_modules/@jest/core/build/watch.js @@ -0,0 +1,666 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = watch; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _ansiEscapes() { + const data = _interopRequireDefault(require('ansi-escapes')); + _ansiEscapes = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _exit() { + const data = _interopRequireDefault(require('exit')); + _exit = function () { + return data; + }; + return data; +} +function _slash() { + const data = _interopRequireDefault(require('slash')); + _slash = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _jestValidate() { + const data = require('jest-validate'); + _jestValidate = function () { + return data; + }; + return data; +} +function _jestWatcher() { + const data = require('jest-watcher'); + _jestWatcher = function () { + return data; + }; + return data; +} +var _FailedTestsCache = _interopRequireDefault(require('./FailedTestsCache')); +var _SearchSource = _interopRequireDefault(require('./SearchSource')); +var _getChangedFilesPromise = _interopRequireDefault( + require('./getChangedFilesPromise') +); +var _activeFiltersMessage = _interopRequireDefault( + require('./lib/activeFiltersMessage') +); +var _createContext = _interopRequireDefault(require('./lib/createContext')); +var _isValidPath = _interopRequireDefault(require('./lib/isValidPath')); +var _updateGlobalConfig = _interopRequireDefault( + require('./lib/updateGlobalConfig') +); +var _watchPluginsHelpers = require('./lib/watchPluginsHelpers'); +var _FailedTestsInteractive = _interopRequireDefault( + require('./plugins/FailedTestsInteractive') +); +var _Quit = _interopRequireDefault(require('./plugins/Quit')); +var _TestNamePattern = _interopRequireDefault( + require('./plugins/TestNamePattern') +); +var _TestPathPattern = _interopRequireDefault( + require('./plugins/TestPathPattern') +); +var _UpdateSnapshots = _interopRequireDefault( + require('./plugins/UpdateSnapshots') +); +var _UpdateSnapshotsInteractive = _interopRequireDefault( + require('./plugins/UpdateSnapshotsInteractive') +); +var _runJest = _interopRequireDefault(require('./runJest')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const {print: preRunMessagePrint} = _jestUtil().preRunMessage; +let hasExitListener = false; +const INTERNAL_PLUGINS = [ + _FailedTestsInteractive.default, + _TestPathPattern.default, + _TestNamePattern.default, + _UpdateSnapshots.default, + _UpdateSnapshotsInteractive.default, + _Quit.default +]; +const RESERVED_KEY_PLUGINS = new Map([ + [ + _UpdateSnapshots.default, + { + forbiddenOverwriteMessage: 'updating snapshots', + key: 'u' + } + ], + [ + _UpdateSnapshotsInteractive.default, + { + forbiddenOverwriteMessage: 'updating snapshots interactively', + key: 'i' + } + ], + [ + _Quit.default, + { + forbiddenOverwriteMessage: 'quitting watch mode' + } + ] +]); +async function watch( + initialGlobalConfig, + contexts, + outputStream, + hasteMapInstances, + stdin = process.stdin, + hooks = new (_jestWatcher().JestHook)(), + filter +) { + // `globalConfig` will be constantly updated and reassigned as a result of + // watch mode interactions. + let globalConfig = initialGlobalConfig; + let activePlugin; + globalConfig = (0, _updateGlobalConfig.default)(globalConfig, { + mode: globalConfig.watch ? 'watch' : 'watchAll', + passWithNoTests: true + }); + const updateConfigAndRun = ({ + bail, + changedSince, + collectCoverage, + collectCoverageFrom, + coverageDirectory, + coverageReporters, + findRelatedTests, + mode, + nonFlagArgs, + notify, + notifyMode, + onlyFailures, + reporters, + testNamePattern, + testPathPattern, + updateSnapshot, + verbose + } = {}) => { + const previousUpdateSnapshot = globalConfig.updateSnapshot; + globalConfig = (0, _updateGlobalConfig.default)(globalConfig, { + bail, + changedSince, + collectCoverage, + collectCoverageFrom, + coverageDirectory, + coverageReporters, + findRelatedTests, + mode, + nonFlagArgs, + notify, + notifyMode, + onlyFailures, + reporters, + testNamePattern, + testPathPattern, + updateSnapshot, + verbose + }); + startRun(globalConfig); + globalConfig = (0, _updateGlobalConfig.default)(globalConfig, { + // updateSnapshot is not sticky after a run. + updateSnapshot: + previousUpdateSnapshot === 'all' ? 'none' : previousUpdateSnapshot + }); + }; + const watchPlugins = INTERNAL_PLUGINS.map( + InternalPlugin => + new InternalPlugin({ + stdin, + stdout: outputStream + }) + ); + watchPlugins.forEach(plugin => { + const hookSubscriber = hooks.getSubscriber(); + if (plugin.apply) { + plugin.apply(hookSubscriber); + } + }); + if (globalConfig.watchPlugins != null) { + const watchPluginKeys = new Map(); + for (const plugin of watchPlugins) { + const reservedInfo = RESERVED_KEY_PLUGINS.get(plugin.constructor) || {}; + const key = reservedInfo.key || getPluginKey(plugin, globalConfig); + if (!key) { + continue; + } + const {forbiddenOverwriteMessage} = reservedInfo; + watchPluginKeys.set(key, { + forbiddenOverwriteMessage, + overwritable: forbiddenOverwriteMessage == null, + plugin + }); + } + for (const pluginWithConfig of globalConfig.watchPlugins) { + let plugin; + try { + const ThirdPartyPlugin = await (0, _jestUtil().requireOrImportModule)( + pluginWithConfig.path + ); + plugin = new ThirdPartyPlugin({ + config: pluginWithConfig.config, + stdin, + stdout: outputStream + }); + } catch (error) { + const errorWithContext = new Error( + `Failed to initialize watch plugin "${_chalk().default.bold( + (0, _slash().default)( + path().relative(process.cwd(), pluginWithConfig.path) + ) + )}":\n\n${(0, _jestMessageUtil().formatExecError)( + error, + contexts[0].config, + { + noStackTrace: false + } + )}` + ); + delete errorWithContext.stack; + return Promise.reject(errorWithContext); + } + checkForConflicts(watchPluginKeys, plugin, globalConfig); + const hookSubscriber = hooks.getSubscriber(); + if (plugin.apply) { + plugin.apply(hookSubscriber); + } + watchPlugins.push(plugin); + } + } + const failedTestsCache = new _FailedTestsCache.default(); + let searchSources = contexts.map(context => ({ + context, + searchSource: new _SearchSource.default(context) + })); + let isRunning = false; + let testWatcher; + let shouldDisplayWatchUsage = true; + let isWatchUsageDisplayed = false; + const emitFileChange = () => { + if (hooks.isUsed('onFileChange')) { + const projects = searchSources.map(({context, searchSource}) => ({ + config: context.config, + testPaths: searchSource.findMatchingTests('').tests.map(t => t.path) + })); + hooks.getEmitter().onFileChange({ + projects + }); + } + }; + emitFileChange(); + hasteMapInstances.forEach((hasteMapInstance, index) => { + hasteMapInstance.on('change', ({eventsQueue, hasteFS, moduleMap}) => { + const validPaths = eventsQueue.filter(({filePath}) => + (0, _isValidPath.default)(globalConfig, filePath) + ); + if (validPaths.length) { + const context = (contexts[index] = (0, _createContext.default)( + contexts[index].config, + { + hasteFS, + moduleMap + } + )); + activePlugin = null; + searchSources = searchSources.slice(); + searchSources[index] = { + context, + searchSource: new _SearchSource.default(context) + }; + emitFileChange(); + startRun(globalConfig); + } + }); + }); + if (!hasExitListener) { + hasExitListener = true; + process.on('exit', () => { + if (activePlugin) { + outputStream.write(_ansiEscapes().default.cursorDown()); + outputStream.write(_ansiEscapes().default.eraseDown); + } + }); + } + const startRun = globalConfig => { + if (isRunning) { + return Promise.resolve(null); + } + testWatcher = new (_jestWatcher().TestWatcher)({ + isWatchMode: true + }); + _jestUtil().isInteractive && + outputStream.write(_jestUtil().specialChars.CLEAR); + preRunMessagePrint(outputStream); + isRunning = true; + const configs = contexts.map(context => context.config); + const changedFilesPromise = (0, _getChangedFilesPromise.default)( + globalConfig, + configs + ); + return (0, _runJest.default)({ + changedFilesPromise, + contexts, + failedTestsCache, + filter, + globalConfig, + jestHooks: hooks.getEmitter(), + onComplete: results => { + isRunning = false; + hooks.getEmitter().onTestRunComplete(results); + + // Create a new testWatcher instance so that re-runs won't be blocked. + // The old instance that was passed to Jest will still be interrupted + // and prevent test runs from the previous run. + testWatcher = new (_jestWatcher().TestWatcher)({ + isWatchMode: true + }); + + // Do not show any Watch Usage related stuff when running in a + // non-interactive environment + if (_jestUtil().isInteractive) { + if (shouldDisplayWatchUsage) { + outputStream.write(usage(globalConfig, watchPlugins)); + shouldDisplayWatchUsage = false; // hide Watch Usage after first run + isWatchUsageDisplayed = true; + } else { + outputStream.write(showToggleUsagePrompt()); + shouldDisplayWatchUsage = false; + isWatchUsageDisplayed = false; + } + } else { + outputStream.write('\n'); + } + failedTestsCache.setTestResults(results.testResults); + }, + outputStream, + startRun, + testWatcher + }).catch(error => + // Errors thrown inside `runJest`, e.g. by resolvers, are caught here for + // continuous watch mode execution. We need to reprint them to the + // terminal and give just a little bit of extra space so they fit below + // `preRunMessagePrint` message nicely. + console.error( + `\n\n${(0, _jestMessageUtil().formatExecError)( + error, + contexts[0].config, + { + noStackTrace: false + } + )}` + ) + ); + }; + const onKeypress = key => { + if ( + key === _jestWatcher().KEYS.CONTROL_C || + key === _jestWatcher().KEYS.CONTROL_D + ) { + if (typeof stdin.setRawMode === 'function') { + stdin.setRawMode(false); + } + outputStream.write('\n'); + (0, _exit().default)(0); + return; + } + if (activePlugin != null && activePlugin.onKey) { + // if a plugin is activate, Jest should let it handle keystrokes, so ignore + // them here + activePlugin.onKey(key); + return; + } + + // Abort test run + const pluginKeys = (0, _watchPluginsHelpers.getSortedUsageRows)( + watchPlugins, + globalConfig + ).map(usage => Number(usage.key).toString(16)); + if ( + isRunning && + testWatcher && + ['q', _jestWatcher().KEYS.ENTER, 'a', 'o', 'f'] + .concat(pluginKeys) + .includes(key) + ) { + testWatcher.setState({ + interrupted: true + }); + return; + } + const matchingWatchPlugin = (0, + _watchPluginsHelpers.filterInteractivePlugins)( + watchPlugins, + globalConfig + ).find(plugin => getPluginKey(plugin, globalConfig) === key); + if (matchingWatchPlugin != null) { + if (isRunning) { + testWatcher.setState({ + interrupted: true + }); + return; + } + // "activate" the plugin, which has jest ignore keystrokes so the plugin + // can handle them + activePlugin = matchingWatchPlugin; + if (activePlugin.run) { + activePlugin.run(globalConfig, updateConfigAndRun).then( + shouldRerun => { + activePlugin = null; + if (shouldRerun) { + updateConfigAndRun(); + } + }, + () => { + activePlugin = null; + onCancelPatternPrompt(); + } + ); + } else { + activePlugin = null; + } + } + switch (key) { + case _jestWatcher().KEYS.ENTER: + startRun(globalConfig); + break; + case 'a': + globalConfig = (0, _updateGlobalConfig.default)(globalConfig, { + mode: 'watchAll', + testNamePattern: '', + testPathPattern: '' + }); + startRun(globalConfig); + break; + case 'c': + updateConfigAndRun({ + mode: 'watch', + testNamePattern: '', + testPathPattern: '' + }); + break; + case 'f': + globalConfig = (0, _updateGlobalConfig.default)(globalConfig, { + onlyFailures: !globalConfig.onlyFailures + }); + startRun(globalConfig); + break; + case 'o': + globalConfig = (0, _updateGlobalConfig.default)(globalConfig, { + mode: 'watch', + testNamePattern: '', + testPathPattern: '' + }); + startRun(globalConfig); + break; + case '?': + break; + case 'w': + if (!shouldDisplayWatchUsage && !isWatchUsageDisplayed) { + outputStream.write(_ansiEscapes().default.cursorUp()); + outputStream.write(_ansiEscapes().default.eraseDown); + outputStream.write(usage(globalConfig, watchPlugins)); + isWatchUsageDisplayed = true; + shouldDisplayWatchUsage = false; + } + break; + } + }; + const onCancelPatternPrompt = () => { + outputStream.write(_ansiEscapes().default.cursorHide); + outputStream.write(_jestUtil().specialChars.CLEAR); + outputStream.write(usage(globalConfig, watchPlugins)); + outputStream.write(_ansiEscapes().default.cursorShow); + }; + if (typeof stdin.setRawMode === 'function') { + stdin.setRawMode(true); + stdin.resume(); + stdin.setEncoding('utf8'); + stdin.on('data', onKeypress); + } + startRun(globalConfig); + return Promise.resolve(); +} +const checkForConflicts = (watchPluginKeys, plugin, globalConfig) => { + const key = getPluginKey(plugin, globalConfig); + if (!key) { + return; + } + const conflictor = watchPluginKeys.get(key); + if (!conflictor || conflictor.overwritable) { + watchPluginKeys.set(key, { + overwritable: false, + plugin + }); + return; + } + let error; + if (conflictor.forbiddenOverwriteMessage) { + error = ` + Watch plugin ${_chalk().default.bold.red( + getPluginIdentifier(plugin) + )} attempted to register key ${_chalk().default.bold.red(`<${key}>`)}, + that is reserved internally for ${_chalk().default.bold.red( + conflictor.forbiddenOverwriteMessage + )}. + Please change the configuration key for this plugin.`.trim(); + } else { + const plugins = [conflictor.plugin, plugin] + .map(p => _chalk().default.bold.red(getPluginIdentifier(p))) + .join(' and '); + error = ` + Watch plugins ${plugins} both attempted to register key ${_chalk().default.bold.red( + `<${key}>` + )}. + Please change the key configuration for one of the conflicting plugins to avoid overlap.`.trim(); + } + throw new (_jestValidate().ValidationError)( + 'Watch plugin configuration error', + error + ); +}; +const getPluginIdentifier = plugin => + // This breaks as `displayName` is not defined as a static, but since + // WatchPlugin is an interface, and it is my understanding interface + // static fields are not definable anymore, no idea how to circumvent + // this :-( + // @ts-expect-error: leave `displayName` be. + plugin.constructor.displayName || plugin.constructor.name; +const getPluginKey = (plugin, globalConfig) => { + if (typeof plugin.getUsageInfo === 'function') { + return ( + plugin.getUsageInfo(globalConfig) || { + key: null + } + ).key; + } + return null; +}; +const usage = (globalConfig, watchPlugins, delimiter = '\n') => { + const messages = [ + (0, _activeFiltersMessage.default)(globalConfig), + globalConfig.testPathPattern || globalConfig.testNamePattern + ? `${_chalk().default.dim(' \u203A Press ')}c${_chalk().default.dim( + ' to clear filters.' + )}` + : null, + `\n${_chalk().default.bold('Watch Usage')}`, + globalConfig.watch + ? `${_chalk().default.dim(' \u203A Press ')}a${_chalk().default.dim( + ' to run all tests.' + )}` + : null, + globalConfig.onlyFailures + ? `${_chalk().default.dim(' \u203A Press ')}f${_chalk().default.dim( + ' to quit "only failed tests" mode.' + )}` + : `${_chalk().default.dim(' \u203A Press ')}f${_chalk().default.dim( + ' to run only failed tests.' + )}`, + (globalConfig.watchAll || + globalConfig.testPathPattern || + globalConfig.testNamePattern) && + !globalConfig.noSCM + ? `${_chalk().default.dim(' \u203A Press ')}o${_chalk().default.dim( + ' to only run tests related to changed files.' + )}` + : null, + ...(0, _watchPluginsHelpers.getSortedUsageRows)( + watchPlugins, + globalConfig + ).map( + plugin => + `${_chalk().default.dim(' \u203A Press')} ${ + plugin.key + } ${_chalk().default.dim(`to ${plugin.prompt}.`)}` + ), + `${_chalk().default.dim(' \u203A Press ')}Enter${_chalk().default.dim( + ' to trigger a test run.' + )}` + ]; + return `${messages.filter(message => !!message).join(delimiter)}\n`; +}; +const showToggleUsagePrompt = () => + '\n' + + `${_chalk().default.bold('Watch Usage: ')}${_chalk().default.dim( + 'Press ' + )}w${_chalk().default.dim(' to show more.')}`; diff --git a/node_modules/@jest/core/package.json b/node_modules/@jest/core/package.json new file mode 100644 index 0000000..84b7080 --- /dev/null +++ b/node_modules/@jest/core/package.json @@ -0,0 +1,102 @@ +{ + "name": "@jest/core", + "description": "Delightful JavaScript Testing.", + "version": "29.2.2", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/console": "^29.2.1", + "@jest/reporters": "^29.2.2", + "@jest/test-result": "^29.2.1", + "@jest/transform": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "jest-changed-files": "^29.2.0", + "jest-config": "^29.2.2", + "jest-haste-map": "^29.2.1", + "jest-message-util": "^29.2.1", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.2.2", + "jest-resolve-dependencies": "^29.2.2", + "jest-runner": "^29.2.2", + "jest-runtime": "^29.2.2", + "jest-snapshot": "^29.2.2", + "jest-util": "^29.2.1", + "jest-validate": "^29.2.2", + "jest-watcher": "^29.2.2", + "micromatch": "^4.0.4", + "pretty-format": "^29.2.1", + "slash": "^3.0.0", + "strip-ansi": "^6.0.0" + }, + "devDependencies": { + "@jest/test-sequencer": "^29.2.2", + "@jest/test-utils": "^29.2.1", + "@types/exit": "^0.1.30", + "@types/graceful-fs": "^4.1.3", + "@types/micromatch": "^4.0.1" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-core" + }, + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "homepage": "https://jestjs.io/", + "license": "MIT", + "keywords": [ + "ava", + "babel", + "coverage", + "easy", + "expect", + "facebook", + "immersive", + "instant", + "jasmine", + "jest", + "jsdom", + "mocha", + "mocking", + "painless", + "qunit", + "runner", + "sandboxed", + "snapshot", + "tap", + "tape", + "test", + "testing", + "typescript", + "watch" + ], + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/@jest/environment/LICENSE b/node_modules/@jest/environment/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/environment/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/environment/build/index.d.ts b/node_modules/@jest/environment/build/index.d.ts new file mode 100644 index 0000000..2ee0410 --- /dev/null +++ b/node_modules/@jest/environment/build/index.d.ts @@ -0,0 +1,356 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import type {Circus} from '@jest/types'; +import type {Config} from '@jest/types'; +import type {Context} from 'vm'; +import type {Global} from '@jest/types'; +import type {LegacyFakeTimers} from '@jest/fake-timers'; +import type {Mocked} from 'jest-mock'; +import type {ModernFakeTimers} from '@jest/fake-timers'; +import type {ModuleMocker} from 'jest-mock'; + +export declare type EnvironmentContext = { + console: Console; + docblockPragmas: Record>; + testPath: string; +}; + +export declare interface Jest { + /** + * Advances all timers by `msToRun` milliseconds. All pending "macro-tasks" + * that have been queued via `setTimeout()` or `setInterval()`, and would be + * executed within this time frame will be executed. + */ + advanceTimersByTime(msToRun: number): void; + /** + * Advances all timers by the needed milliseconds so that only the next + * timeouts/intervals will run. Optionally, you can provide steps, so it will + * run steps amount of next timeouts/intervals. + */ + advanceTimersToNextTimer(steps?: number): void; + /** + * Disables automatic mocking in the module loader. + */ + autoMockOff(): Jest; + /** + * Enables automatic mocking in the module loader. + */ + autoMockOn(): Jest; + /** + * Clears the `mock.calls`, `mock.instances`, `mock.contexts` and `mock.results` properties of + * all mocks. Equivalent to calling `.mockClear()` on every mocked function. + */ + clearAllMocks(): Jest; + /** + * Removes any pending timers from the timer system. If any timers have been + * scheduled, they will be cleared and will never have the opportunity to + * execute in the future. + */ + clearAllTimers(): void; + /** + * Given the name of a module, use the automatic mocking system to generate a + * mocked version of the module for you. + * + * This is useful when you want to create a manual mock that extends the + * automatic mock's behavior. + */ + createMockFromModule(moduleName: string): Mocked; + /** + * Indicates that the module system should never return a mocked version of + * the specified module and its dependencies. + */ + deepUnmock(moduleName: string): Jest; + /** + * Disables automatic mocking in the module loader. + * + * After this method is called, all `require()`s will return the real + * versions of each module (rather than a mocked version). + */ + disableAutomock(): Jest; + /** + * When using `babel-jest`, calls to `jest.mock()` will automatically be hoisted + * to the top of the code block. Use this method if you want to explicitly + * avoid this behavior. + */ + doMock( + moduleName: string, + moduleFactory?: () => T, + options?: { + virtual?: boolean; + }, + ): Jest; + /** + * When using `babel-jest`, calls to `jest.unmock()` will automatically be hoisted + * to the top of the code block. Use this method if you want to explicitly + * avoid this behavior. + */ + dontMock(moduleName: string): Jest; + /** + * Enables automatic mocking in the module loader. + */ + enableAutomock(): Jest; + /** + * Creates a mock function. Optionally takes a mock implementation. + */ + fn: ModuleMocker['fn']; + /** + * Given the name of a module, use the automatic mocking system to generate a + * mocked version of the module for you. + * + * This is useful when you want to create a manual mock that extends the + * automatic mock's behavior. + * + * @deprecated Use `jest.createMockFromModule()` instead + */ + genMockFromModule(moduleName: string): Mocked; + /** + * When mocking time, `Date.now()` will also be mocked. If you for some reason + * need access to the real current time, you can invoke this function. + * + * @remarks + * Not available when using legacy fake timers implementation. + */ + getRealSystemTime(): number; + /** + * Retrieves the seed value. It will be randomly generated for each test run + * or can be manually set via the `--seed` CLI argument. + */ + getSeed(): number; + /** + * Returns the number of fake timers still left to run. + */ + getTimerCount(): number; + /** + * Returns the current time in ms of the fake timer clock. + */ + now(): number; + /** + * Determines if the given function is a mocked function. + */ + isMockFunction: ModuleMocker['isMockFunction']; + /** + * `jest.isolateModules()` goes a step further than `jest.resetModules()` and + * creates a sandbox registry for the modules that are loaded inside the callback + * function. This is useful to isolate specific modules for every test so that + * local module state doesn't conflict between tests. + */ + isolateModules(fn: () => void): Jest; + /** + * Mocks a module with an auto-mocked version when it is being required. + */ + mock( + moduleName: string, + moduleFactory?: () => T, + options?: { + virtual?: boolean; + }, + ): Jest; + /** + * Mocks a module with the provided module factory when it is being imported. + */ + unstable_mockModule( + moduleName: string, + moduleFactory: () => T | Promise, + options?: { + virtual?: boolean; + }, + ): Jest; + /** + * Returns the actual module instead of a mock, bypassing all checks on + * whether the module should receive a mock implementation or not. + * + * @example + * ```js + * jest.mock('../myModule', () => { + * // Require the original module to not be mocked... + * const originalModule = jest.requireActual('../myModule'); + * + * return { + * __esModule: true, // Use it when dealing with esModules + * ...originalModule, + * getRandom: jest.fn().mockReturnValue(10), + * }; + * }); + * + * const getRandom = require('../myModule').getRandom; + * + * getRandom(); // Always returns 10 + * ``` + */ + requireActual(moduleName: string): T; + /** + * Wraps types of the `source` object and its deep members with type definitions + * of Jest mock function. Pass `{shallow: true}` option to disable the deeply + * mocked behavior. + */ + mocked: ModuleMocker['mocked']; + /** + * Returns a mock module instead of the actual module, bypassing all checks + * on whether the module should be required normally or not. + */ + requireMock(moduleName: string): T; + /** + * Resets the state of all mocks. Equivalent to calling `.mockReset()` on + * every mocked function. + */ + resetAllMocks(): Jest; + /** + * Resets the module registry - the cache of all required modules. This is + * useful to isolate modules where local state might conflict between tests. + */ + resetModules(): Jest; + /** + * Restores all mocks back to their original value. Equivalent to calling + * `.mockRestore()` on every mocked function. + * + * Beware that `jest.restoreAllMocks()` only works when the mock was created + * with `jest.spyOn()`; other mocks will require you to manually restore them. + */ + restoreAllMocks(): Jest; + /** + * Runs failed tests n-times until they pass or until the max number of + * retries is exhausted. + * + * If `logErrorsBeforeRetry` is enabled, Jest will log the error(s) that caused + * the test to fail to the console, providing visibility on why a retry occurred. + * retries is exhausted. + * + * @remarks + * Only available with `jest-circus` runner. + */ + retryTimes( + numRetries: number, + options?: { + logErrorsBeforeRetry?: boolean; + }, + ): Jest; + /** + * Exhausts tasks queued by `setImmediate()`. + * + * @remarks + * Only available when using legacy fake timers implementation. + */ + runAllImmediates(): void; + /** + * Exhausts the micro-task queue (usually interfaced in node via + * `process.nextTick()`). + */ + runAllTicks(): void; + /** + * Exhausts the macro-task queue (i.e., all tasks queued by `setTimeout()` + * and `setInterval()`). + */ + runAllTimers(): void; + /** + * Executes only the macro-tasks that are currently pending (i.e., only the + * tasks that have been queued by `setTimeout()` or `setInterval()` up to this + * point). If any of the currently pending macro-tasks schedule new + * macro-tasks, those new tasks will not be executed by this call. + */ + runOnlyPendingTimers(): void; + /** + * Explicitly supplies the mock object that the module system should return + * for the specified module. + * + * @remarks + * It is recommended to use `jest.mock()` instead. The `jest.mock()` API's second + * argument is a module factory instead of the expected exported module object. + */ + setMock(moduleName: string, moduleExports: unknown): Jest; + /** + * Set the current system time used by fake timers. Simulates a user changing + * the system clock while your program is running. It affects the current time, + * but it does not in itself cause e.g. timers to fire; they will fire exactly + * as they would have done without the call to `jest.setSystemTime()`. + * + * @remarks + * Not available when using legacy fake timers implementation. + */ + setSystemTime(now?: number | Date): void; + /** + * Set the default timeout interval for tests and before/after hooks in + * milliseconds. + * + * @remarks + * The default timeout interval is 5 seconds if this method is not called. + */ + setTimeout(timeout: number): Jest; + /** + * Creates a mock function similar to `jest.fn()` but also tracks calls to + * `object[methodName]`. + * + * Optional third argument of `accessType` can be either 'get' or 'set', which + * proves to be useful when you want to spy on a getter or a setter, respectively. + * + * @remarks + * By default, `jest.spyOn()` also calls the spied method. This is different + * behavior from most other test libraries. + */ + spyOn: ModuleMocker['spyOn']; + /** + * Indicates that the module system should never return a mocked version of + * the specified module from `require()` (e.g. that it should always return the + * real module). + */ + unmock(moduleName: string): Jest; + /** + * Instructs Jest to use fake versions of the global date, performance, + * time and timer APIs. Fake timers implementation is backed by + * [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers). + * + * @remarks + * Calling `jest.useFakeTimers()` once again in the same test file would reinstall + * fake timers using the provided options. + */ + useFakeTimers( + fakeTimersConfig?: Config.FakeTimersConfig | Config.LegacyFakeTimersConfig, + ): Jest; + /** + * Instructs Jest to restore the original implementations of the global date, + * performance, time and timer APIs. + */ + useRealTimers(): Jest; +} + +export declare class JestEnvironment { + constructor(config: JestEnvironmentConfig, context: EnvironmentContext); + global: Global.Global; + fakeTimers: LegacyFakeTimers | null; + fakeTimersModern: ModernFakeTimers | null; + moduleMocker: ModuleMocker | null; + getVmContext(): Context | null; + setup(): Promise; + teardown(): Promise; + handleTestEvent?: Circus.EventHandler; + exportConditions?: () => Array; +} + +export declare interface JestEnvironmentConfig { + projectConfig: Config.ProjectConfig; + globalConfig: Config.GlobalConfig; +} + +export declare interface JestImportMeta extends ImportMeta { + jest: Jest; +} + +export declare type Module = NodeModule; + +export declare type ModuleWrapper = ( + this: Module['exports'], + module: Module, + exports: Module['exports'], + require: Module['require'], + __dirname: string, + __filename: Module['filename'], + jest?: Jest, + ...sandboxInjectedGlobals: Array +) => unknown; + +export {}; diff --git a/node_modules/@jest/environment/build/index.js b/node_modules/@jest/environment/build/index.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/environment/build/index.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/environment/package.json b/node_modules/@jest/environment/package.json new file mode 100644 index 0000000..273826f --- /dev/null +++ b/node_modules/@jest/environment/package.json @@ -0,0 +1,32 @@ +{ + "name": "@jest/environment", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-environment" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/fake-timers": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/node": "*", + "jest-mock": "^29.2.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/@jest/expect-utils/LICENSE b/node_modules/@jest/expect-utils/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/expect-utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/expect-utils/README.md b/node_modules/@jest/expect-utils/README.md new file mode 100644 index 0000000..12ae8b2 --- /dev/null +++ b/node_modules/@jest/expect-utils/README.md @@ -0,0 +1,5 @@ +# `@jest/expect-utils` + +This module exports some utils for the `expect` function used in [Jest](https://jestjs.io/). + +You probably don't want to use this package directly. E.g. if you're writing [custom matcher](https://jestjs.io/docs/expect#expectextendmatchers), you should use the injected [`this.equals`](https://jestjs.io/docs/expect#thisequalsa-b). diff --git a/node_modules/@jest/expect-utils/build/immutableUtils.js b/node_modules/@jest/expect-utils/build/immutableUtils.js new file mode 100644 index 0000000..8f578bc --- /dev/null +++ b/node_modules/@jest/expect-utils/build/immutableUtils.js @@ -0,0 +1,66 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.isImmutableList = isImmutableList; +exports.isImmutableOrderedKeyed = isImmutableOrderedKeyed; +exports.isImmutableOrderedSet = isImmutableOrderedSet; +exports.isImmutableRecord = isImmutableRecord; +exports.isImmutableUnorderedKeyed = isImmutableUnorderedKeyed; +exports.isImmutableUnorderedSet = isImmutableUnorderedSet; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +// SENTINEL constants are from https://github.com/immutable-js/immutable-js/tree/main/src/predicates +const IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; +const IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; +const IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; +const IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; +const IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@'; +function isObjectLiteral(source) { + return source != null && typeof source === 'object' && !Array.isArray(source); +} +function isImmutableUnorderedKeyed(source) { + return Boolean( + source && + isObjectLiteral(source) && + source[IS_KEYED_SENTINEL] && + !source[IS_ORDERED_SENTINEL] + ); +} +function isImmutableUnorderedSet(source) { + return Boolean( + source && + isObjectLiteral(source) && + source[IS_SET_SENTINEL] && + !source[IS_ORDERED_SENTINEL] + ); +} +function isImmutableList(source) { + return Boolean(source && isObjectLiteral(source) && source[IS_LIST_SENTINEL]); +} +function isImmutableOrderedKeyed(source) { + return Boolean( + source && + isObjectLiteral(source) && + source[IS_KEYED_SENTINEL] && + source[IS_ORDERED_SENTINEL] + ); +} +function isImmutableOrderedSet(source) { + return Boolean( + source && + isObjectLiteral(source) && + source[IS_SET_SENTINEL] && + source[IS_ORDERED_SENTINEL] + ); +} +function isImmutableRecord(source) { + return Boolean(source && isObjectLiteral(source) && source[IS_RECORD_SYMBOL]); +} diff --git a/node_modules/@jest/expect-utils/build/index.d.ts b/node_modules/@jest/expect-utils/build/index.d.ts new file mode 100644 index 0000000..ffe3aa3 --- /dev/null +++ b/node_modules/@jest/expect-utils/build/index.d.ts @@ -0,0 +1,93 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare const arrayBufferEquality: ( + a: unknown, + b: unknown, +) => boolean | undefined; + +export declare function emptyObject(obj: unknown): boolean; + +export declare const equals: EqualsFunction; + +export declare type EqualsFunction = ( + a: unknown, + b: unknown, + customTesters?: Array, + strictCheck?: boolean, +) => boolean; + +export declare const getObjectSubset: ( + object: any, + subset: any, + seenReferences?: WeakMap, +) => any; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +declare type GetPath = { + hasEndProp?: boolean; + endPropIsDefined?: boolean; + lastTraversedObject: unknown; + traversedPath: Array; + value?: unknown; +}; + +export declare const getPath: ( + object: Record, + propertyPath: string | Array, +) => GetPath; + +export declare function isA(typeName: string, value: unknown): value is T; + +export declare const isError: (value: unknown) => value is Error; + +export declare const isOneline: ( + expected: unknown, + received: unknown, +) => boolean; + +export declare const iterableEquality: ( + a: any, + b: any, + aStack?: Array, + bStack?: Array, +) => boolean | undefined; + +export declare const partition: ( + items: T[], + predicate: (arg: T) => boolean, +) => [T[], T[]]; + +export declare const pathAsArray: (propertyPath: string) => Array; + +export declare const sparseArrayEquality: ( + a: unknown, + b: unknown, +) => boolean | undefined; + +export declare const subsetEquality: ( + object: unknown, + subset: unknown, +) => boolean | undefined; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +export declare type Tester = (a: any, b: any) => boolean | undefined; + +export declare const typeEquality: (a: any, b: any) => boolean | undefined; + +export {}; diff --git a/node_modules/@jest/expect-utils/build/index.js b/node_modules/@jest/expect-utils/build/index.js new file mode 100644 index 0000000..e84aca9 --- /dev/null +++ b/node_modules/@jest/expect-utils/build/index.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +var _exportNames = { + equals: true, + isA: true +}; +Object.defineProperty(exports, 'equals', { + enumerable: true, + get: function () { + return _jasmineUtils.equals; + } +}); +Object.defineProperty(exports, 'isA', { + enumerable: true, + get: function () { + return _jasmineUtils.isA; + } +}); +var _jasmineUtils = require('./jasmineUtils'); +var _utils = require('./utils'); +Object.keys(_utils).forEach(function (key) { + if (key === 'default' || key === '__esModule') return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _utils[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _utils[key]; + } + }); +}); diff --git a/node_modules/@jest/expect-utils/build/jasmineUtils.js b/node_modules/@jest/expect-utils/build/jasmineUtils.js new file mode 100644 index 0000000..5ba932b --- /dev/null +++ b/node_modules/@jest/expect-utils/build/jasmineUtils.js @@ -0,0 +1,210 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.equals = void 0; +exports.isA = isA; +/* +Copyright (c) 2008-2016 Pivotal Labs + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +*/ + +// Extracted out of jasmine 2.5.2 +const equals = (a, b, customTesters, strictCheck) => { + customTesters = customTesters || []; + return eq(a, b, [], [], customTesters, strictCheck); +}; +exports.equals = equals; +function isAsymmetric(obj) { + return !!obj && isA('Function', obj.asymmetricMatch); +} +function asymmetricMatch(a, b) { + const asymmetricA = isAsymmetric(a); + const asymmetricB = isAsymmetric(b); + if (asymmetricA && asymmetricB) { + return undefined; + } + if (asymmetricA) { + return a.asymmetricMatch(b); + } + if (asymmetricB) { + return b.asymmetricMatch(a); + } +} + +// Equality function lovingly adapted from isEqual in +// [Underscore](http://underscorejs.org) +function eq(a, b, aStack, bStack, customTesters, strictCheck) { + let result = true; + const asymmetricResult = asymmetricMatch(a, b); + if (asymmetricResult !== undefined) { + return asymmetricResult; + } + for (let i = 0; i < customTesters.length; i++) { + const customTesterResult = customTesters[i](a, b); + if (customTesterResult !== undefined) { + return customTesterResult; + } + } + if (a instanceof Error && b instanceof Error) { + return a.message == b.message; + } + if (Object.is(a, b)) { + return true; + } + // A strict comparison is necessary because `null == undefined`. + if (a === null || b === null) { + return a === b; + } + const className = Object.prototype.toString.call(a); + if (className != Object.prototype.toString.call(b)) { + return false; + } + switch (className) { + case '[object Boolean]': + case '[object String]': + case '[object Number]': + if (typeof a !== typeof b) { + // One is a primitive, one a `new Primitive()` + return false; + } else if (typeof a !== 'object' && typeof b !== 'object') { + // both are proper primitives + return Object.is(a, b); + } else { + // both are `new Primitive()`s + return Object.is(a.valueOf(), b.valueOf()); + } + case '[object Date]': + // Coerce dates to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + return +a == +b; + // RegExps are compared by their source patterns and flags. + case '[object RegExp]': + return a.source === b.source && a.flags === b.flags; + } + if (typeof a !== 'object' || typeof b !== 'object') { + return false; + } + + // Use DOM3 method isEqualNode (IE>=9) + if (isDomNode(a) && isDomNode(b)) { + return a.isEqualNode(b); + } + + // Used to detect circular references. + let length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + // circular references at same depth are equal + // circular reference is not equal to non-circular one + if (aStack[length] === a) { + return bStack[length] === b; + } else if (bStack[length] === b) { + return false; + } + } + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + // Recursively compare objects and arrays. + // Compare array lengths to determine if a deep comparison is necessary. + if (strictCheck && className == '[object Array]' && a.length !== b.length) { + return false; + } + + // Deep compare objects. + const aKeys = keys(a, hasKey); + let key; + const bKeys = keys(b, hasKey); + // Add keys corresponding to asymmetric matchers if they miss in non strict check mode + if (!strictCheck) { + for (let index = 0; index !== bKeys.length; ++index) { + key = bKeys[index]; + if ((isAsymmetric(b[key]) || b[key] === undefined) && !hasKey(a, key)) { + aKeys.push(key); + } + } + for (let index = 0; index !== aKeys.length; ++index) { + key = aKeys[index]; + if ((isAsymmetric(a[key]) || a[key] === undefined) && !hasKey(b, key)) { + bKeys.push(key); + } + } + } + + // Ensure that both objects contain the same number of properties before comparing deep equality. + let size = aKeys.length; + if (bKeys.length !== size) { + return false; + } + while (size--) { + key = aKeys[size]; + + // Deep compare each member + if (strictCheck) + result = + hasKey(b, key) && + eq(a[key], b[key], aStack, bStack, customTesters, strictCheck); + else + result = + (hasKey(b, key) || isAsymmetric(a[key]) || a[key] === undefined) && + eq(a[key], b[key], aStack, bStack, customTesters, strictCheck); + if (!result) { + return false; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return result; +} +function keys(obj, hasKey) { + const keys = []; + for (const key in obj) { + if (hasKey(obj, key)) { + keys.push(key); + } + } + return keys.concat( + Object.getOwnPropertySymbols(obj).filter( + symbol => Object.getOwnPropertyDescriptor(obj, symbol).enumerable + ) + ); +} +function hasKey(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function isA(typeName, value) { + return Object.prototype.toString.apply(value) === `[object ${typeName}]`; +} +function isDomNode(obj) { + return ( + obj !== null && + typeof obj === 'object' && + typeof obj.nodeType === 'number' && + typeof obj.nodeName === 'string' && + typeof obj.isEqualNode === 'function' + ); +} diff --git a/node_modules/@jest/expect-utils/build/types.js b/node_modules/@jest/expect-utils/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/expect-utils/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/expect-utils/build/utils.js b/node_modules/@jest/expect-utils/build/utils.js new file mode 100644 index 0000000..4f0db37 --- /dev/null +++ b/node_modules/@jest/expect-utils/build/utils.js @@ -0,0 +1,394 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.arrayBufferEquality = void 0; +exports.emptyObject = emptyObject; +exports.typeEquality = + exports.subsetEquality = + exports.sparseArrayEquality = + exports.pathAsArray = + exports.partition = + exports.iterableEquality = + exports.isOneline = + exports.isError = + exports.getPath = + exports.getObjectSubset = + void 0; +var _jestGetType = require('jest-get-type'); +var _immutableUtils = require('./immutableUtils'); +var _jasmineUtils = require('./jasmineUtils'); +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +/** + * Checks if `hasOwnProperty(object, key)` up the prototype chain, stopping at `Object.prototype`. + */ +const hasPropertyInObject = (object, key) => { + const shouldTerminate = + !object || typeof object !== 'object' || object === Object.prototype; + if (shouldTerminate) { + return false; + } + return ( + Object.prototype.hasOwnProperty.call(object, key) || + hasPropertyInObject(Object.getPrototypeOf(object), key) + ); +}; +const getPath = (object, propertyPath) => { + if (!Array.isArray(propertyPath)) { + propertyPath = pathAsArray(propertyPath); + } + if (propertyPath.length) { + const lastProp = propertyPath.length === 1; + const prop = propertyPath[0]; + const newObject = object[prop]; + if (!lastProp && (newObject === null || newObject === undefined)) { + // This is not the last prop in the chain. If we keep recursing it will + // hit a `can't access property X of undefined | null`. At this point we + // know that the chain has broken and we can return right away. + return { + hasEndProp: false, + lastTraversedObject: object, + traversedPath: [] + }; + } + const result = getPath(newObject, propertyPath.slice(1)); + if (result.lastTraversedObject === null) { + result.lastTraversedObject = object; + } + result.traversedPath.unshift(prop); + if (lastProp) { + // Does object have the property with an undefined value? + // Although primitive values support bracket notation (above) + // they would throw TypeError for in operator (below). + result.endPropIsDefined = + !(0, _jestGetType.isPrimitive)(object) && prop in object; + result.hasEndProp = newObject !== undefined || result.endPropIsDefined; + if (!result.hasEndProp) { + result.traversedPath.shift(); + } + } + return result; + } + return { + lastTraversedObject: null, + traversedPath: [], + value: object + }; +}; + +// Strip properties from object that are not present in the subset. Useful for +// printing the diff for toMatchObject() without adding unrelated noise. +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +exports.getPath = getPath; +const getObjectSubset = (object, subset, seenReferences = new WeakMap()) => { + /* eslint-enable @typescript-eslint/explicit-module-boundary-types */ + if (Array.isArray(object)) { + if (Array.isArray(subset) && subset.length === object.length) { + // The map method returns correct subclass of subset. + return subset.map((sub, i) => getObjectSubset(object[i], sub)); + } + } else if (object instanceof Date) { + return object; + } else if (isObject(object) && isObject(subset)) { + if ( + (0, _jasmineUtils.equals)(object, subset, [ + iterableEquality, + subsetEquality + ]) + ) { + // Avoid unnecessary copy which might return Object instead of subclass. + return subset; + } + const trimmed = {}; + seenReferences.set(object, trimmed); + Object.keys(object) + .filter(key => hasPropertyInObject(subset, key)) + .forEach(key => { + trimmed[key] = seenReferences.has(object[key]) + ? seenReferences.get(object[key]) + : getObjectSubset(object[key], subset[key], seenReferences); + }); + if (Object.keys(trimmed).length > 0) { + return trimmed; + } + } + return object; +}; +exports.getObjectSubset = getObjectSubset; +const IteratorSymbol = Symbol.iterator; +const hasIterator = object => !!(object != null && object[IteratorSymbol]); + +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +const iterableEquality = ( + a, + b /* eslint-enable @typescript-eslint/explicit-module-boundary-types */, + aStack = [], + bStack = [] +) => { + if ( + typeof a !== 'object' || + typeof b !== 'object' || + Array.isArray(a) || + Array.isArray(b) || + !hasIterator(a) || + !hasIterator(b) + ) { + return undefined; + } + if (a.constructor !== b.constructor) { + return false; + } + let length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + // circular references at same depth are equal + // circular reference is not equal to non-circular one + if (aStack[length] === a) { + return bStack[length] === b; + } + } + aStack.push(a); + bStack.push(b); + const iterableEqualityWithStack = (a, b) => + iterableEquality(a, b, [...aStack], [...bStack]); + if (a.size !== undefined) { + if (a.size !== b.size) { + return false; + } else if ( + (0, _jasmineUtils.isA)('Set', a) || + (0, _immutableUtils.isImmutableUnorderedSet)(a) + ) { + let allFound = true; + for (const aValue of a) { + if (!b.has(aValue)) { + let has = false; + for (const bValue of b) { + const isEqual = (0, _jasmineUtils.equals)(aValue, bValue, [ + iterableEqualityWithStack + ]); + if (isEqual === true) { + has = true; + } + } + if (has === false) { + allFound = false; + break; + } + } + } + // Remove the first value from the stack of traversed values. + aStack.pop(); + bStack.pop(); + return allFound; + } else if ( + (0, _jasmineUtils.isA)('Map', a) || + (0, _immutableUtils.isImmutableUnorderedKeyed)(a) + ) { + let allFound = true; + for (const aEntry of a) { + if ( + !b.has(aEntry[0]) || + !(0, _jasmineUtils.equals)(aEntry[1], b.get(aEntry[0]), [ + iterableEqualityWithStack + ]) + ) { + let has = false; + for (const bEntry of b) { + const matchedKey = (0, _jasmineUtils.equals)(aEntry[0], bEntry[0], [ + iterableEqualityWithStack + ]); + let matchedValue = false; + if (matchedKey === true) { + matchedValue = (0, _jasmineUtils.equals)(aEntry[1], bEntry[1], [ + iterableEqualityWithStack + ]); + } + if (matchedValue === true) { + has = true; + } + } + if (has === false) { + allFound = false; + break; + } + } + } + // Remove the first value from the stack of traversed values. + aStack.pop(); + bStack.pop(); + return allFound; + } + } + const bIterator = b[IteratorSymbol](); + for (const aValue of a) { + const nextB = bIterator.next(); + if ( + nextB.done || + !(0, _jasmineUtils.equals)(aValue, nextB.value, [ + iterableEqualityWithStack + ]) + ) { + return false; + } + } + if (!bIterator.next().done) { + return false; + } + if ( + !(0, _immutableUtils.isImmutableList)(a) && + !(0, _immutableUtils.isImmutableOrderedKeyed)(a) && + !(0, _immutableUtils.isImmutableOrderedSet)(a) && + !(0, _immutableUtils.isImmutableRecord)(a) + ) { + const aEntries = Object.entries(a); + const bEntries = Object.entries(b); + if (!(0, _jasmineUtils.equals)(aEntries, bEntries)) { + return false; + } + } + + // Remove the first value from the stack of traversed values. + aStack.pop(); + bStack.pop(); + return true; +}; +exports.iterableEquality = iterableEquality; +const isObject = a => a !== null && typeof a === 'object'; +const isObjectWithKeys = a => + isObject(a) && + !(a instanceof Error) && + !(a instanceof Array) && + !(a instanceof Date); +const subsetEquality = (object, subset) => { + // subsetEquality needs to keep track of the references + // it has already visited to avoid infinite loops in case + // there are circular references in the subset passed to it. + const subsetEqualityWithContext = + (seenReferences = new WeakMap()) => + (object, subset) => { + if (!isObjectWithKeys(subset)) { + return undefined; + } + return Object.keys(subset).every(key => { + if (isObjectWithKeys(subset[key])) { + if (seenReferences.has(subset[key])) { + return (0, _jasmineUtils.equals)(object[key], subset[key], [ + iterableEquality + ]); + } + seenReferences.set(subset[key], true); + } + const result = + object != null && + hasPropertyInObject(object, key) && + (0, _jasmineUtils.equals)(object[key], subset[key], [ + iterableEquality, + subsetEqualityWithContext(seenReferences) + ]); + // The main goal of using seenReference is to avoid circular node on tree. + // It will only happen within a parent and its child, not a node and nodes next to it (same level) + // We should keep the reference for a parent and its child only + // Thus we should delete the reference immediately so that it doesn't interfere + // other nodes within the same level on tree. + seenReferences.delete(subset[key]); + return result; + }); + }; + return subsetEqualityWithContext()(object, subset); +}; + +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +exports.subsetEquality = subsetEquality; +const typeEquality = (a, b) => { + if (a == null || b == null || a.constructor === b.constructor) { + return undefined; + } + return false; +}; +exports.typeEquality = typeEquality; +const arrayBufferEquality = (a, b) => { + if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer)) { + return undefined; + } + const dataViewA = new DataView(a); + const dataViewB = new DataView(b); + + // Buffers are not equal when they do not have the same byte length + if (dataViewA.byteLength !== dataViewB.byteLength) { + return false; + } + + // Check if every byte value is equal to each other + for (let i = 0; i < dataViewA.byteLength; i++) { + if (dataViewA.getUint8(i) !== dataViewB.getUint8(i)) { + return false; + } + } + return true; +}; +exports.arrayBufferEquality = arrayBufferEquality; +const sparseArrayEquality = (a, b) => { + if (!Array.isArray(a) || !Array.isArray(b)) { + return undefined; + } + + // A sparse array [, , 1] will have keys ["2"] whereas [undefined, undefined, 1] will have keys ["0", "1", "2"] + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + return ( + (0, _jasmineUtils.equals)(a, b, [iterableEquality, typeEquality], true) && + (0, _jasmineUtils.equals)(aKeys, bKeys) + ); +}; +exports.sparseArrayEquality = sparseArrayEquality; +const partition = (items, predicate) => { + const result = [[], []]; + items.forEach(item => result[predicate(item) ? 0 : 1].push(item)); + return result; +}; +exports.partition = partition; +const pathAsArray = propertyPath => { + const properties = []; + if (propertyPath === '') { + properties.push(''); + return properties; + } + + // will match everything that's not a dot or a bracket, and "" for consecutive dots. + const pattern = RegExp('[^.[\\]]+|(?=(?:\\.)(?:\\.|$))', 'g'); + + // Because the regex won't match a dot in the beginning of the path, if present. + if (propertyPath[0] === '.') { + properties.push(''); + } + propertyPath.replace(pattern, match => { + properties.push(match); + return match; + }); + return properties; +}; + +// Copied from https://github.com/graingert/angular.js/blob/a43574052e9775cbc1d7dd8a086752c979b0f020/src/Angular.js#L685-L693 +exports.pathAsArray = pathAsArray; +const isError = value => { + switch (Object.prototype.toString.call(value)) { + case '[object Error]': + case '[object Exception]': + case '[object DOMException]': + return true; + default: + return value instanceof Error; + } +}; +exports.isError = isError; +function emptyObject(obj) { + return obj && typeof obj === 'object' ? !Object.keys(obj).length : false; +} +const MULTILINE_REGEXP = /[\r\n]/; +const isOneline = (expected, received) => + typeof expected === 'string' && + typeof received === 'string' && + (!MULTILINE_REGEXP.test(expected) || !MULTILINE_REGEXP.test(received)); +exports.isOneline = isOneline; diff --git a/node_modules/@jest/expect-utils/package.json b/node_modules/@jest/expect-utils/package.json new file mode 100644 index 0000000..bb8a75f --- /dev/null +++ b/node_modules/@jest/expect-utils/package.json @@ -0,0 +1,35 @@ +{ + "name": "@jest/expect-utils", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/expect-utils" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "jest-get-type": "^29.2.0" + }, + "devDependencies": { + "@tsd/typescript": "~4.8.2", + "immutable": "^4.0.0", + "jest-matcher-utils": "^29.2.2", + "tsd-lite": "^0.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/@jest/expect/LICENSE b/node_modules/@jest/expect/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/expect/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/expect/README.md b/node_modules/@jest/expect/README.md new file mode 100644 index 0000000..81cf1b4 --- /dev/null +++ b/node_modules/@jest/expect/README.md @@ -0,0 +1,5 @@ +# @jest/expect + +This package extends `expect` library with `jest-snapshot` matchers. It exports `jestExpect` object, which can be used as standalone replacement of `expect`. + +The `jestExpect` function used in [Jest](https://jestjs.io/). You can find its documentation [on Jest's website](https://jestjs.io/docs/expect). diff --git a/node_modules/@jest/expect/build/index.d.ts b/node_modules/@jest/expect/build/index.d.ts new file mode 100644 index 0000000..96575a8 --- /dev/null +++ b/node_modules/@jest/expect/build/index.d.ts @@ -0,0 +1,68 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {addSerializer} from 'jest-snapshot'; +import {AsymmetricMatchers} from 'expect'; +import type {BaseExpect} from 'expect'; +import {MatcherContext} from 'expect'; +import {MatcherFunction} from 'expect'; +import {MatcherFunctionWithContext} from 'expect'; +import {Matchers} from 'expect'; +import {MatcherState} from 'expect'; +import {MatcherUtils} from 'expect'; +import type {SnapshotMatchers} from 'jest-snapshot'; + +export {AsymmetricMatchers}; + +declare type Inverse = { + /** + * Inverse next matcher. If you know how to test something, `.not` lets you test its opposite. + */ + not: Matchers; +}; + +export declare type JestExpect = { + (actual: T): JestMatchers & + Inverse> & + PromiseMatchers; + addSnapshotSerializer: typeof addSerializer; +} & BaseExpect & + AsymmetricMatchers & + Inverse>; + +export declare const jestExpect: JestExpect; + +declare type JestMatchers, T> = Matchers & + SnapshotMatchers; + +export {MatcherContext}; + +export {MatcherFunction}; + +export {MatcherFunctionWithContext}; + +export {Matchers}; + +export {MatcherState}; + +export {MatcherUtils}; + +declare type PromiseMatchers = { + /** + * Unwraps the reason of a rejected promise so any other matcher can be chained. + * If the promise is fulfilled the assertion fails. + */ + rejects: JestMatchers, T> & + Inverse, T>>; + /** + * Unwraps the value of a fulfilled promise so any other matcher can be chained. + * If the promise is rejected the assertion fails. + */ + resolves: JestMatchers, T> & + Inverse, T>>; +}; + +export {}; diff --git a/node_modules/@jest/expect/build/index.js b/node_modules/@jest/expect/build/index.js new file mode 100644 index 0000000..b6db0c2 --- /dev/null +++ b/node_modules/@jest/expect/build/index.js @@ -0,0 +1,40 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.jestExpect = void 0; +function _expect() { + const data = require('expect'); + _expect = function () { + return data; + }; + return data; +} +function _jestSnapshot() { + const data = require('jest-snapshot'); + _jestSnapshot = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function createJestExpect() { + _expect().expect.extend({ + toMatchInlineSnapshot: _jestSnapshot().toMatchInlineSnapshot, + toMatchSnapshot: _jestSnapshot().toMatchSnapshot, + toThrowErrorMatchingInlineSnapshot: + _jestSnapshot().toThrowErrorMatchingInlineSnapshot, + toThrowErrorMatchingSnapshot: _jestSnapshot().toThrowErrorMatchingSnapshot + }); + _expect().expect.addSnapshotSerializer = _jestSnapshot().addSerializer; + return _expect().expect; +} +const jestExpect = createJestExpect(); +exports.jestExpect = jestExpect; diff --git a/node_modules/@jest/expect/build/types.js b/node_modules/@jest/expect/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/expect/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/expect/package.json b/node_modules/@jest/expect/package.json new file mode 100644 index 0000000..5c02c4f --- /dev/null +++ b/node_modules/@jest/expect/package.json @@ -0,0 +1,34 @@ +{ + "name": "@jest/expect", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-expect" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "expect": "^29.2.2", + "jest-snapshot": "^29.2.2" + }, + "devDependencies": { + "@tsd/typescript": "~4.8.2", + "tsd-lite": "^0.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/@jest/fake-timers/LICENSE b/node_modules/@jest/fake-timers/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/fake-timers/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/fake-timers/build/index.d.ts b/node_modules/@jest/fake-timers/build/index.d.ts new file mode 100644 index 0000000..e59ed1d --- /dev/null +++ b/node_modules/@jest/fake-timers/build/index.d.ts @@ -0,0 +1,106 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config} from '@jest/types'; +import type {ModuleMocker} from 'jest-mock'; +import {StackTraceConfig} from 'jest-message-util'; + +declare type Callback = (...args: Array) => void; + +export declare class LegacyFakeTimers { + private _cancelledTicks; + private readonly _config; + private _disposed; + private _fakeTimerAPIs; + private _fakingTime; + private _global; + private _immediates; + private readonly _maxLoops; + private readonly _moduleMocker; + private _now; + private _ticks; + private readonly _timerAPIs; + private _timers; + private _uuidCounter; + private readonly _timerConfig; + constructor({ + global, + moduleMocker, + timerConfig, + config, + maxLoops, + }: { + global: typeof globalThis; + moduleMocker: ModuleMocker; + timerConfig: TimerConfig; + config: StackTraceConfig; + maxLoops?: number; + }); + clearAllTimers(): void; + dispose(): void; + reset(): void; + now(): number; + runAllTicks(): void; + runAllImmediates(): void; + private _runImmediate; + runAllTimers(): void; + runOnlyPendingTimers(): void; + advanceTimersToNextTimer(steps?: number): void; + advanceTimersByTime(msToRun: number): void; + runWithRealTimers(cb: Callback): void; + useRealTimers(): void; + useFakeTimers(): void; + getTimerCount(): number; + private _checkFakeTimers; + private _createMocks; + private _fakeClearTimer; + private _fakeClearImmediate; + private _fakeNextTick; + private _fakeRequestAnimationFrame; + private _fakeSetImmediate; + private _fakeSetInterval; + private _fakeSetTimeout; + private _getNextTimerHandleAndExpiry; + private _runTimerHandle; +} + +export declare class ModernFakeTimers { + private _clock; + private readonly _config; + private _fakingTime; + private readonly _global; + private readonly _fakeTimers; + constructor({ + global, + config, + }: { + global: typeof globalThis; + config: Config.ProjectConfig; + }); + clearAllTimers(): void; + dispose(): void; + runAllTimers(): void; + runOnlyPendingTimers(): void; + advanceTimersToNextTimer(steps?: number): void; + advanceTimersByTime(msToRun: number): void; + runAllTicks(): void; + useRealTimers(): void; + useFakeTimers(fakeTimersConfig?: Config.FakeTimersConfig): void; + reset(): void; + setSystemTime(now?: number | Date): void; + getRealSystemTime(): number; + now(): number; + getTimerCount(): number; + private _checkFakeTimers; + private _toSinonFakeTimersConfig; +} + +declare type TimerConfig = { + idToRef: (id: number) => Ref; + refToId: (ref: Ref) => number | void; +}; + +export {}; diff --git a/node_modules/@jest/fake-timers/build/index.js b/node_modules/@jest/fake-timers/build/index.js new file mode 100644 index 0000000..776d3e5 --- /dev/null +++ b/node_modules/@jest/fake-timers/build/index.js @@ -0,0 +1,22 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'LegacyFakeTimers', { + enumerable: true, + get: function () { + return _legacyFakeTimers.default; + } +}); +Object.defineProperty(exports, 'ModernFakeTimers', { + enumerable: true, + get: function () { + return _modernFakeTimers.default; + } +}); +var _legacyFakeTimers = _interopRequireDefault(require('./legacyFakeTimers')); +var _modernFakeTimers = _interopRequireDefault(require('./modernFakeTimers')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} diff --git a/node_modules/@jest/fake-timers/build/legacyFakeTimers.js b/node_modules/@jest/fake-timers/build/legacyFakeTimers.js new file mode 100644 index 0000000..52d7693 --- /dev/null +++ b/node_modules/@jest/fake-timers/build/legacyFakeTimers.js @@ -0,0 +1,545 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _util() { + const data = require('util'); + _util = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/prefer-spread-eventually */ + +const MS_IN_A_YEAR = 31536000000; +class FakeTimers { + _cancelledTicks; + _config; + _disposed; + _fakeTimerAPIs; + _fakingTime = false; + _global; + _immediates; + _maxLoops; + _moduleMocker; + _now; + _ticks; + _timerAPIs; + _timers; + _uuidCounter; + _timerConfig; + constructor({global, moduleMocker, timerConfig, config, maxLoops}) { + this._global = global; + this._timerConfig = timerConfig; + this._config = config; + this._maxLoops = maxLoops || 100000; + this._uuidCounter = 1; + this._moduleMocker = moduleMocker; + + // Store original timer APIs for future reference + this._timerAPIs = { + cancelAnimationFrame: global.cancelAnimationFrame, + clearImmediate: global.clearImmediate, + clearInterval: global.clearInterval, + clearTimeout: global.clearTimeout, + nextTick: global.process && global.process.nextTick, + requestAnimationFrame: global.requestAnimationFrame, + setImmediate: global.setImmediate, + setInterval: global.setInterval, + setTimeout: global.setTimeout + }; + this._disposed = false; + this.reset(); + } + clearAllTimers() { + this._immediates = []; + this._timers.clear(); + } + dispose() { + this._disposed = true; + this.clearAllTimers(); + } + reset() { + this._cancelledTicks = {}; + this._now = 0; + this._ticks = []; + this._immediates = []; + this._timers = new Map(); + } + now() { + if (this._fakingTime) { + return this._now; + } + return Date.now(); + } + runAllTicks() { + this._checkFakeTimers(); + // Only run a generous number of ticks and then bail. + // This is just to help avoid recursive loops + let i; + for (i = 0; i < this._maxLoops; i++) { + const tick = this._ticks.shift(); + if (tick === undefined) { + break; + } + if ( + !Object.prototype.hasOwnProperty.call(this._cancelledTicks, tick.uuid) + ) { + // Callback may throw, so update the map prior calling. + this._cancelledTicks[tick.uuid] = true; + tick.callback(); + } + } + if (i === this._maxLoops) { + throw new Error( + `Ran ${this._maxLoops} ticks, and there are still more! ` + + "Assuming we've hit an infinite recursion and bailing out..." + ); + } + } + runAllImmediates() { + this._checkFakeTimers(); + // Only run a generous number of immediates and then bail. + let i; + for (i = 0; i < this._maxLoops; i++) { + const immediate = this._immediates.shift(); + if (immediate === undefined) { + break; + } + this._runImmediate(immediate); + } + if (i === this._maxLoops) { + throw new Error( + `Ran ${this._maxLoops} immediates, and there are still more! Assuming ` + + "we've hit an infinite recursion and bailing out..." + ); + } + } + _runImmediate(immediate) { + try { + immediate.callback(); + } finally { + this._fakeClearImmediate(immediate.uuid); + } + } + runAllTimers() { + this._checkFakeTimers(); + this.runAllTicks(); + this.runAllImmediates(); + + // Only run a generous number of timers and then bail. + // This is just to help avoid recursive loops + let i; + for (i = 0; i < this._maxLoops; i++) { + const nextTimerHandleAndExpiry = this._getNextTimerHandleAndExpiry(); + + // If there are no more timer handles, stop! + if (nextTimerHandleAndExpiry === null) { + break; + } + const [nextTimerHandle, expiry] = nextTimerHandleAndExpiry; + this._now = expiry; + this._runTimerHandle(nextTimerHandle); + + // Some of the immediate calls could be enqueued + // during the previous handling of the timers, we should + // run them as well. + if (this._immediates.length) { + this.runAllImmediates(); + } + if (this._ticks.length) { + this.runAllTicks(); + } + } + if (i === this._maxLoops) { + throw new Error( + `Ran ${this._maxLoops} timers, and there are still more! ` + + "Assuming we've hit an infinite recursion and bailing out..." + ); + } + } + runOnlyPendingTimers() { + // We need to hold the current shape of `this._timers` because existing + // timers can add new ones to the map and hence would run more than necessary. + // See https://github.com/facebook/jest/pull/4608 for details + const timerEntries = Array.from(this._timers.entries()); + this._checkFakeTimers(); + this._immediates.forEach(this._runImmediate, this); + timerEntries + .sort(([, left], [, right]) => left.expiry - right.expiry) + .forEach(([timerHandle, timer]) => { + this._now = timer.expiry; + this._runTimerHandle(timerHandle); + }); + } + advanceTimersToNextTimer(steps = 1) { + if (steps < 1) { + return; + } + const nextExpiry = Array.from(this._timers.values()).reduce( + (minExpiry, timer) => { + if (minExpiry === null || timer.expiry < minExpiry) return timer.expiry; + return minExpiry; + }, + null + ); + if (nextExpiry !== null) { + this.advanceTimersByTime(nextExpiry - this._now); + this.advanceTimersToNextTimer(steps - 1); + } + } + advanceTimersByTime(msToRun) { + this._checkFakeTimers(); + // Only run a generous number of timers and then bail. + // This is just to help avoid recursive loops + let i; + for (i = 0; i < this._maxLoops; i++) { + const timerHandleAndExpiry = this._getNextTimerHandleAndExpiry(); + + // If there are no more timer handles, stop! + if (timerHandleAndExpiry === null) { + break; + } + const [timerHandle, nextTimerExpiry] = timerHandleAndExpiry; + if (this._now + msToRun < nextTimerExpiry) { + // There are no timers between now and the target we're running to + break; + } else { + msToRun -= nextTimerExpiry - this._now; + this._now = nextTimerExpiry; + this._runTimerHandle(timerHandle); + } + } + + // Advance the clock by whatever time we still have left to run + this._now += msToRun; + if (i === this._maxLoops) { + throw new Error( + `Ran ${this._maxLoops} timers, and there are still more! ` + + "Assuming we've hit an infinite recursion and bailing out..." + ); + } + } + runWithRealTimers(cb) { + const prevClearImmediate = this._global.clearImmediate; + const prevClearInterval = this._global.clearInterval; + const prevClearTimeout = this._global.clearTimeout; + const prevNextTick = this._global.process.nextTick; + const prevSetImmediate = this._global.setImmediate; + const prevSetInterval = this._global.setInterval; + const prevSetTimeout = this._global.setTimeout; + this.useRealTimers(); + let cbErr = null; + let errThrown = false; + try { + cb(); + } catch (e) { + errThrown = true; + cbErr = e; + } + this._global.clearImmediate = prevClearImmediate; + this._global.clearInterval = prevClearInterval; + this._global.clearTimeout = prevClearTimeout; + this._global.process.nextTick = prevNextTick; + this._global.setImmediate = prevSetImmediate; + this._global.setInterval = prevSetInterval; + this._global.setTimeout = prevSetTimeout; + if (errThrown) { + throw cbErr; + } + } + useRealTimers() { + const global = this._global; + if (typeof global.cancelAnimationFrame === 'function') { + (0, _jestUtil().setGlobal)( + global, + 'cancelAnimationFrame', + this._timerAPIs.cancelAnimationFrame + ); + } + if (typeof global.clearImmediate === 'function') { + (0, _jestUtil().setGlobal)( + global, + 'clearImmediate', + this._timerAPIs.clearImmediate + ); + } + (0, _jestUtil().setGlobal)( + global, + 'clearInterval', + this._timerAPIs.clearInterval + ); + (0, _jestUtil().setGlobal)( + global, + 'clearTimeout', + this._timerAPIs.clearTimeout + ); + if (typeof global.requestAnimationFrame === 'function') { + (0, _jestUtil().setGlobal)( + global, + 'requestAnimationFrame', + this._timerAPIs.requestAnimationFrame + ); + } + if (typeof global.setImmediate === 'function') { + (0, _jestUtil().setGlobal)( + global, + 'setImmediate', + this._timerAPIs.setImmediate + ); + } + (0, _jestUtil().setGlobal)( + global, + 'setInterval', + this._timerAPIs.setInterval + ); + (0, _jestUtil().setGlobal)( + global, + 'setTimeout', + this._timerAPIs.setTimeout + ); + global.process.nextTick = this._timerAPIs.nextTick; + this._fakingTime = false; + } + useFakeTimers() { + this._createMocks(); + const global = this._global; + if (typeof global.cancelAnimationFrame === 'function') { + (0, _jestUtil().setGlobal)( + global, + 'cancelAnimationFrame', + this._fakeTimerAPIs.cancelAnimationFrame + ); + } + if (typeof global.clearImmediate === 'function') { + (0, _jestUtil().setGlobal)( + global, + 'clearImmediate', + this._fakeTimerAPIs.clearImmediate + ); + } + (0, _jestUtil().setGlobal)( + global, + 'clearInterval', + this._fakeTimerAPIs.clearInterval + ); + (0, _jestUtil().setGlobal)( + global, + 'clearTimeout', + this._fakeTimerAPIs.clearTimeout + ); + if (typeof global.requestAnimationFrame === 'function') { + (0, _jestUtil().setGlobal)( + global, + 'requestAnimationFrame', + this._fakeTimerAPIs.requestAnimationFrame + ); + } + if (typeof global.setImmediate === 'function') { + (0, _jestUtil().setGlobal)( + global, + 'setImmediate', + this._fakeTimerAPIs.setImmediate + ); + } + (0, _jestUtil().setGlobal)( + global, + 'setInterval', + this._fakeTimerAPIs.setInterval + ); + (0, _jestUtil().setGlobal)( + global, + 'setTimeout', + this._fakeTimerAPIs.setTimeout + ); + global.process.nextTick = this._fakeTimerAPIs.nextTick; + this._fakingTime = true; + } + getTimerCount() { + this._checkFakeTimers(); + return this._timers.size + this._immediates.length + this._ticks.length; + } + _checkFakeTimers() { + if (!this._fakingTime) { + this._global.console.warn( + 'A function to advance timers was called but the timers APIs are not mocked ' + + 'with fake timers. Call `jest.useFakeTimers({legacyFakeTimers: true})` ' + + 'in this test file or enable fake timers for all tests by setting ' + + "{'enableGlobally': true, 'legacyFakeTimers': true} in " + + `Jest configuration file.\nStack Trace:\n${(0, + _jestMessageUtil().formatStackTrace)( + new Error().stack, + this._config, + { + noStackTrace: false + } + )}` + ); + } + } + _createMocks() { + const fn = implementation => this._moduleMocker.fn(implementation); + const promisifiableFakeSetTimeout = fn(this._fakeSetTimeout.bind(this)); + // @ts-expect-error: no index + promisifiableFakeSetTimeout[_util().promisify.custom] = (delay, arg) => + new Promise(resolve => promisifiableFakeSetTimeout(resolve, delay, arg)); + this._fakeTimerAPIs = { + cancelAnimationFrame: fn(this._fakeClearTimer.bind(this)), + clearImmediate: fn(this._fakeClearImmediate.bind(this)), + clearInterval: fn(this._fakeClearTimer.bind(this)), + clearTimeout: fn(this._fakeClearTimer.bind(this)), + nextTick: fn(this._fakeNextTick.bind(this)), + requestAnimationFrame: fn(this._fakeRequestAnimationFrame.bind(this)), + setImmediate: fn(this._fakeSetImmediate.bind(this)), + setInterval: fn(this._fakeSetInterval.bind(this)), + setTimeout: promisifiableFakeSetTimeout + }; + } + _fakeClearTimer(timerRef) { + const uuid = this._timerConfig.refToId(timerRef); + if (uuid) { + this._timers.delete(String(uuid)); + } + } + _fakeClearImmediate(uuid) { + this._immediates = this._immediates.filter( + immediate => immediate.uuid !== uuid + ); + } + _fakeNextTick(callback, ...args) { + if (this._disposed) { + return; + } + const uuid = String(this._uuidCounter++); + this._ticks.push({ + callback: () => callback.apply(null, args), + uuid + }); + const cancelledTicks = this._cancelledTicks; + this._timerAPIs.nextTick(() => { + if (!Object.prototype.hasOwnProperty.call(cancelledTicks, uuid)) { + // Callback may throw, so update the map prior calling. + cancelledTicks[uuid] = true; + callback.apply(null, args); + } + }); + } + _fakeRequestAnimationFrame(callback) { + return this._fakeSetTimeout(() => { + // TODO: Use performance.now() once it's mocked + callback(this._now); + }, 1000 / 60); + } + _fakeSetImmediate(callback, ...args) { + if (this._disposed) { + return null; + } + const uuid = String(this._uuidCounter++); + this._immediates.push({ + callback: () => callback.apply(null, args), + uuid + }); + this._timerAPIs.setImmediate(() => { + if (!this._disposed) { + if (this._immediates.find(x => x.uuid === uuid)) { + try { + callback.apply(null, args); + } finally { + this._fakeClearImmediate(uuid); + } + } + } + }); + return uuid; + } + _fakeSetInterval(callback, intervalDelay, ...args) { + if (this._disposed) { + return null; + } + if (intervalDelay == null) { + intervalDelay = 0; + } + const uuid = this._uuidCounter++; + this._timers.set(String(uuid), { + callback: () => callback.apply(null, args), + expiry: this._now + intervalDelay, + interval: intervalDelay, + type: 'interval' + }); + return this._timerConfig.idToRef(uuid); + } + _fakeSetTimeout(callback, delay, ...args) { + if (this._disposed) { + return null; + } + + // eslint-disable-next-line no-bitwise + delay = Number(delay) | 0; + const uuid = this._uuidCounter++; + this._timers.set(String(uuid), { + callback: () => callback.apply(null, args), + expiry: this._now + delay, + interval: undefined, + type: 'timeout' + }); + return this._timerConfig.idToRef(uuid); + } + _getNextTimerHandleAndExpiry() { + let nextTimerHandle = null; + let soonestTime = MS_IN_A_YEAR; + this._timers.forEach((timer, uuid) => { + if (timer.expiry < soonestTime) { + soonestTime = timer.expiry; + nextTimerHandle = uuid; + } + }); + if (nextTimerHandle === null) { + return null; + } + return [nextTimerHandle, soonestTime]; + } + _runTimerHandle(timerHandle) { + const timer = this._timers.get(timerHandle); + if (!timer) { + // Timer has been cleared - we'll hit this when a timer is cleared within + // another timer in runOnlyPendingTimers + return; + } + switch (timer.type) { + case 'timeout': + this._timers.delete(timerHandle); + timer.callback(); + break; + case 'interval': + timer.expiry = this._now + (timer.interval || 0); + timer.callback(); + break; + default: + throw new Error(`Unexpected timer type: ${timer.type}`); + } + } +} +exports.default = FakeTimers; diff --git a/node_modules/@jest/fake-timers/build/modernFakeTimers.js b/node_modules/@jest/fake-timers/build/modernFakeTimers.js new file mode 100644 index 0000000..1af3a8c --- /dev/null +++ b/node_modules/@jest/fake-timers/build/modernFakeTimers.js @@ -0,0 +1,164 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _fakeTimers() { + const data = require('@sinonjs/fake-timers'); + _fakeTimers = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class FakeTimers { + _clock; + _config; + _fakingTime; + _global; + _fakeTimers; + constructor({global, config}) { + this._global = global; + this._config = config; + this._fakingTime = false; + this._fakeTimers = (0, _fakeTimers().withGlobal)(global); + } + clearAllTimers() { + if (this._fakingTime) { + this._clock.reset(); + } + } + dispose() { + this.useRealTimers(); + } + runAllTimers() { + if (this._checkFakeTimers()) { + this._clock.runAll(); + } + } + runOnlyPendingTimers() { + if (this._checkFakeTimers()) { + this._clock.runToLast(); + } + } + advanceTimersToNextTimer(steps = 1) { + if (this._checkFakeTimers()) { + for (let i = steps; i > 0; i--) { + this._clock.next(); + // Fire all timers at this point: https://github.com/sinonjs/fake-timers/issues/250 + this._clock.tick(0); + if (this._clock.countTimers() === 0) { + break; + } + } + } + } + advanceTimersByTime(msToRun) { + if (this._checkFakeTimers()) { + this._clock.tick(msToRun); + } + } + runAllTicks() { + if (this._checkFakeTimers()) { + // @ts-expect-error - doesn't exist? + this._clock.runMicrotasks(); + } + } + useRealTimers() { + if (this._fakingTime) { + this._clock.uninstall(); + this._fakingTime = false; + } + } + useFakeTimers(fakeTimersConfig) { + if (this._fakingTime) { + this._clock.uninstall(); + } + this._clock = this._fakeTimers.install( + this._toSinonFakeTimersConfig(fakeTimersConfig) + ); + this._fakingTime = true; + } + reset() { + if (this._checkFakeTimers()) { + const {now} = this._clock; + this._clock.reset(); + this._clock.setSystemTime(now); + } + } + setSystemTime(now) { + if (this._checkFakeTimers()) { + this._clock.setSystemTime(now); + } + } + getRealSystemTime() { + return Date.now(); + } + now() { + if (this._fakingTime) { + return this._clock.now; + } + return Date.now(); + } + getTimerCount() { + if (this._checkFakeTimers()) { + return this._clock.countTimers(); + } + return 0; + } + _checkFakeTimers() { + if (!this._fakingTime) { + this._global.console.warn( + 'A function to advance timers was called but the timers APIs are not replaced ' + + 'with fake timers. Call `jest.useFakeTimers()` in this test file or enable ' + + "fake timers for all tests by setting 'fakeTimers': {'enableGlobally': true} " + + `in Jest configuration file.\nStack Trace:\n${(0, + _jestMessageUtil().formatStackTrace)( + new Error().stack, + this._config, + { + noStackTrace: false + } + )}` + ); + } + return this._fakingTime; + } + _toSinonFakeTimersConfig(fakeTimersConfig = {}) { + fakeTimersConfig = { + ...this._config.fakeTimers, + ...fakeTimersConfig + }; + const advanceTimeDelta = + typeof fakeTimersConfig.advanceTimers === 'number' + ? fakeTimersConfig.advanceTimers + : undefined; + const toFake = new Set(Object.keys(this._fakeTimers.timers)); + fakeTimersConfig.doNotFake?.forEach(nameOfFakeableAPI => { + toFake.delete(nameOfFakeableAPI); + }); + return { + advanceTimeDelta, + loopLimit: fakeTimersConfig.timerLimit || 100_000, + now: fakeTimersConfig.now ?? Date.now(), + shouldAdvanceTime: Boolean(fakeTimersConfig.advanceTimers), + shouldClearNativeTimers: true, + toFake: Array.from(toFake) + }; + } +} +exports.default = FakeTimers; diff --git a/node_modules/@jest/fake-timers/package.json b/node_modules/@jest/fake-timers/package.json new file mode 100644 index 0000000..80cfb43 --- /dev/null +++ b/node_modules/@jest/fake-timers/package.json @@ -0,0 +1,38 @@ +{ + "name": "@jest/fake-timers", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-fake-timers" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/types": "^29.2.1", + "@sinonjs/fake-timers": "^9.1.2", + "@types/node": "*", + "jest-message-util": "^29.2.1", + "jest-mock": "^29.2.2", + "jest-util": "^29.2.1" + }, + "devDependencies": { + "@jest/test-utils": "^29.2.1", + "@types/sinonjs__fake-timers": "^8.1.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/@jest/globals/LICENSE b/node_modules/@jest/globals/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/globals/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/globals/build/index.d.ts b/node_modules/@jest/globals/build/index.d.ts new file mode 100644 index 0000000..367dda8 --- /dev/null +++ b/node_modules/@jest/globals/build/index.d.ts @@ -0,0 +1,67 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type { Jest } from '@jest/environment'; +import type { JestExpect } from '@jest/expect'; +import type { Global } from '@jest/types'; +import type { ClassLike, FunctionLike, Mock as JestMock, Mocked as JestMocked, MockedClass as JestMockedClass, MockedFunction as JestMockedFunction, MockedObject as JestMockedObject, Spied as JestSpied, SpiedClass as JestSpiedClass, SpiedFunction as JestSpiedFunction, SpiedGetter as JestSpiedGetter, SpiedSetter as JestSpiedSetter, UnknownFunction } from 'jest-mock'; +export declare const expect: JestExpect; +export declare const it: Global.GlobalAdditions['it']; +export declare const test: Global.GlobalAdditions['test']; +export declare const fit: Global.GlobalAdditions['fit']; +export declare const xit: Global.GlobalAdditions['xit']; +export declare const xtest: Global.GlobalAdditions['xtest']; +export declare const describe: Global.GlobalAdditions['describe']; +export declare const xdescribe: Global.GlobalAdditions['xdescribe']; +export declare const fdescribe: Global.GlobalAdditions['fdescribe']; +export declare const beforeAll: Global.GlobalAdditions['beforeAll']; +export declare const beforeEach: Global.GlobalAdditions['beforeEach']; +export declare const afterEach: Global.GlobalAdditions['afterEach']; +export declare const afterAll: Global.GlobalAdditions['afterAll']; +declare const jest: Jest; +declare namespace jest { + /** + * Constructs the type of a mock function, e.g. the return type of `jest.fn()`. + */ + type Mock = JestMock; + /** + * Wraps a class, function or object type with Jest mock type definitions. + */ + type Mocked = JestMocked; + /** + * Wraps a class type with Jest mock type definitions. + */ + type MockedClass = JestMockedClass; + /** + * Wraps a function type with Jest mock type definitions. + */ + type MockedFunction = JestMockedFunction; + /** + * Wraps an object type with Jest mock type definitions. + */ + type MockedObject = JestMockedObject; + /** + * Constructs the type of a spied class or function. + */ + type Spied = JestSpied; + /** + * Constructs the type of a spied class. + */ + type SpiedClass = JestSpiedClass; + /** + * Constructs the type of a spied function. + */ + type SpiedFunction = JestSpiedFunction; + /** + * Constructs the type of a spied getter. + */ + type SpiedGetter = JestSpiedGetter; + /** + * Constructs the type of a spied setter. + */ + type SpiedSetter = JestSpiedSetter; +} +export { jest }; diff --git a/node_modules/@jest/globals/build/index.js b/node_modules/@jest/globals/build/index.js new file mode 100644 index 0000000..c64513c --- /dev/null +++ b/node_modules/@jest/globals/build/index.js @@ -0,0 +1,14 @@ +'use strict'; + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// eslint-disable-next-line @typescript-eslint/no-namespace + +throw new Error( + 'Do not import `@jest/globals` outside of the Jest test environment' +); diff --git a/node_modules/@jest/globals/package.json b/node_modules/@jest/globals/package.json new file mode 100644 index 0000000..9b64c85 --- /dev/null +++ b/node_modules/@jest/globals/package.json @@ -0,0 +1,32 @@ +{ + "name": "@jest/globals", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-globals" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/environment": "^29.2.2", + "@jest/expect": "^29.2.2", + "@jest/types": "^29.2.1", + "jest-mock": "^29.2.2" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/@jest/reporters/LICENSE b/node_modules/@jest/reporters/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/reporters/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/reporters/assets/jest_logo.png b/node_modules/@jest/reporters/assets/jest_logo.png new file mode 100644 index 0000000..1e8274d Binary files /dev/null and b/node_modules/@jest/reporters/assets/jest_logo.png differ diff --git a/node_modules/@jest/reporters/build/BaseReporter.js b/node_modules/@jest/reporters/build/BaseReporter.js new file mode 100644 index 0000000..23bae33 --- /dev/null +++ b/node_modules/@jest/reporters/build/BaseReporter.js @@ -0,0 +1,48 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const {remove: preRunMessageRemove} = _jestUtil().preRunMessage; +class BaseReporter { + _error; + log(message) { + process.stderr.write(`${message}\n`); + } + onRunStart(_results, _options) { + preRunMessageRemove(process.stderr); + } + + /* eslint-disable @typescript-eslint/no-empty-function */ + onTestCaseResult(_test, _testCaseResult) {} + onTestResult(_test, _testResult, _results) {} + onTestStart(_test) {} + onRunComplete(_testContexts, _aggregatedResults) {} + /* eslint-enable */ + + _setError(error) { + this._error = error; + } + + // Return an error that occurred during reporting. This error will + // define whether the test run was successful or failed. + getLastError() { + return this._error; + } +} +exports.default = BaseReporter; diff --git a/node_modules/@jest/reporters/build/CoverageReporter.js b/node_modules/@jest/reporters/build/CoverageReporter.js new file mode 100644 index 0000000..8b7c229 --- /dev/null +++ b/node_modules/@jest/reporters/build/CoverageReporter.js @@ -0,0 +1,560 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _v8Coverage() { + const data = require('@bcoe/v8-coverage'); + _v8Coverage = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _glob() { + const data = _interopRequireDefault(require('glob')); + _glob = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _istanbulLibCoverage() { + const data = _interopRequireDefault(require('istanbul-lib-coverage')); + _istanbulLibCoverage = function () { + return data; + }; + return data; +} +function _istanbulLibReport() { + const data = _interopRequireDefault(require('istanbul-lib-report')); + _istanbulLibReport = function () { + return data; + }; + return data; +} +function _istanbulLibSourceMaps() { + const data = _interopRequireDefault(require('istanbul-lib-source-maps')); + _istanbulLibSourceMaps = function () { + return data; + }; + return data; +} +function _istanbulReports() { + const data = _interopRequireDefault(require('istanbul-reports')); + _istanbulReports = function () { + return data; + }; + return data; +} +function _v8ToIstanbul() { + const data = _interopRequireDefault(require('v8-to-istanbul')); + _v8ToIstanbul = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _jestWorker() { + const data = require('jest-worker'); + _jestWorker = function () { + return data; + }; + return data; +} +var _BaseReporter = _interopRequireDefault(require('./BaseReporter')); +var _getWatermarks = _interopRequireDefault(require('./getWatermarks')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const FAIL_COLOR = _chalk().default.bold.red; +const RUNNING_TEST_COLOR = _chalk().default.bold.dim; +class CoverageReporter extends _BaseReporter.default { + _context; + _coverageMap; + _globalConfig; + _sourceMapStore; + _v8CoverageResults; + static filename = __filename; + constructor(globalConfig, context) { + super(); + this._context = context; + this._coverageMap = _istanbulLibCoverage().default.createCoverageMap({}); + this._globalConfig = globalConfig; + this._sourceMapStore = + _istanbulLibSourceMaps().default.createSourceMapStore(); + this._v8CoverageResults = []; + } + onTestResult(_test, testResult) { + if (testResult.v8Coverage) { + this._v8CoverageResults.push(testResult.v8Coverage); + return; + } + if (testResult.coverage) { + this._coverageMap.merge(testResult.coverage); + } + } + async onRunComplete(testContexts, aggregatedResults) { + await this._addUntestedFiles(testContexts); + const {map, reportContext} = await this._getCoverageResult(); + try { + const coverageReporters = this._globalConfig.coverageReporters || []; + if (!this._globalConfig.useStderr && coverageReporters.length < 1) { + coverageReporters.push('text-summary'); + } + coverageReporters.forEach(reporter => { + let additionalOptions = {}; + if (Array.isArray(reporter)) { + [reporter, additionalOptions] = reporter; + } + _istanbulReports() + .default.create(reporter, { + maxCols: process.stdout.columns || Infinity, + ...additionalOptions + }) + .execute(reportContext); + }); + aggregatedResults.coverageMap = map; + } catch (e) { + console.error( + _chalk().default.red(` + Failed to write coverage reports: + ERROR: ${e.toString()} + STACK: ${e.stack} + `) + ); + } + this._checkThreshold(map); + } + async _addUntestedFiles(testContexts) { + const files = []; + testContexts.forEach(context => { + const config = context.config; + if ( + this._globalConfig.collectCoverageFrom && + this._globalConfig.collectCoverageFrom.length + ) { + context.hasteFS + .matchFilesWithGlob( + this._globalConfig.collectCoverageFrom, + config.rootDir + ) + .forEach(filePath => + files.push({ + config, + path: filePath + }) + ); + } + }); + if (!files.length) { + return; + } + if (_jestUtil().isInteractive) { + process.stderr.write( + RUNNING_TEST_COLOR('Running coverage on untested files...') + ); + } + let worker; + if (this._globalConfig.maxWorkers <= 1) { + worker = require('./CoverageWorker'); + } else { + worker = new (_jestWorker().Worker)(require.resolve('./CoverageWorker'), { + exposedMethods: ['worker'], + forkOptions: { + serialization: 'json' + }, + maxRetries: 2, + numWorkers: this._globalConfig.maxWorkers + }); + } + const instrumentation = files.map(async fileObj => { + const filename = fileObj.path; + const config = fileObj.config; + const hasCoverageData = this._v8CoverageResults.some(v8Res => + v8Res.some(innerRes => innerRes.result.url === filename) + ); + if ( + !hasCoverageData && + !this._coverageMap.data[filename] && + 'worker' in worker + ) { + try { + const result = await worker.worker({ + config, + context: { + changedFiles: + this._context.changedFiles && + Array.from(this._context.changedFiles), + sourcesRelatedToTestsInChangedFiles: + this._context.sourcesRelatedToTestsInChangedFiles && + Array.from(this._context.sourcesRelatedToTestsInChangedFiles) + }, + globalConfig: this._globalConfig, + path: filename + }); + if (result) { + if (result.kind === 'V8Coverage') { + this._v8CoverageResults.push([ + { + codeTransformResult: undefined, + result: result.result + } + ]); + } else { + this._coverageMap.addFileCoverage(result.coverage); + } + } + } catch (error) { + console.error( + _chalk().default.red( + [ + `Failed to collect coverage from ${filename}`, + `ERROR: ${error.message}`, + `STACK: ${error.stack}` + ].join('\n') + ) + ); + } + } + }); + try { + await Promise.all(instrumentation); + } catch { + // Do nothing; errors were reported earlier to the console. + } + if (_jestUtil().isInteractive) { + (0, _jestUtil().clearLine)(process.stderr); + } + if (worker && 'end' in worker && typeof worker.end === 'function') { + await worker.end(); + } + } + _checkThreshold(map) { + const {coverageThreshold} = this._globalConfig; + if (coverageThreshold) { + function check(name, thresholds, actuals) { + return ['statements', 'branches', 'lines', 'functions'].reduce( + (errors, key) => { + const actual = actuals[key].pct; + const actualUncovered = actuals[key].total - actuals[key].covered; + const threshold = thresholds[key]; + if (threshold !== undefined) { + if (threshold < 0) { + if (threshold * -1 < actualUncovered) { + errors.push( + `Jest: Uncovered count for ${key} (${actualUncovered}) ` + + `exceeds ${name} threshold (${-1 * threshold})` + ); + } + } else if (actual < threshold) { + errors.push( + `Jest: "${name}" coverage threshold for ${key} (${threshold}%) not met: ${actual}%` + ); + } + } + return errors; + }, + [] + ); + } + const THRESHOLD_GROUP_TYPES = { + GLOB: 'glob', + GLOBAL: 'global', + PATH: 'path' + }; + const coveredFiles = map.files(); + const thresholdGroups = Object.keys(coverageThreshold); + const groupTypeByThresholdGroup = {}; + const filesByGlob = {}; + const coveredFilesSortedIntoThresholdGroup = coveredFiles.reduce( + (files, file) => { + const pathOrGlobMatches = thresholdGroups.reduce( + (agg, thresholdGroup) => { + // Preserve trailing slash, but not required if root dir + // See https://github.com/facebook/jest/issues/12703 + const resolvedThresholdGroup = path().resolve(thresholdGroup); + const suffix = + (thresholdGroup.endsWith(path().sep) || + (process.platform === 'win32' && + thresholdGroup.endsWith('/'))) && + !resolvedThresholdGroup.endsWith(path().sep) + ? path().sep + : ''; + const absoluteThresholdGroup = `${resolvedThresholdGroup}${suffix}`; + + // The threshold group might be a path: + + if (file.indexOf(absoluteThresholdGroup) === 0) { + groupTypeByThresholdGroup[thresholdGroup] = + THRESHOLD_GROUP_TYPES.PATH; + return agg.concat([[file, thresholdGroup]]); + } + + // If the threshold group is not a path it might be a glob: + + // Note: glob.sync is slow. By memoizing the files matching each glob + // (rather than recalculating it for each covered file) we save a tonne + // of execution time. + if (filesByGlob[absoluteThresholdGroup] === undefined) { + filesByGlob[absoluteThresholdGroup] = _glob() + .default.sync(absoluteThresholdGroup) + .map(filePath => path().resolve(filePath)); + } + if (filesByGlob[absoluteThresholdGroup].indexOf(file) > -1) { + groupTypeByThresholdGroup[thresholdGroup] = + THRESHOLD_GROUP_TYPES.GLOB; + return agg.concat([[file, thresholdGroup]]); + } + return agg; + }, + [] + ); + if (pathOrGlobMatches.length > 0) { + return files.concat(pathOrGlobMatches); + } + + // Neither a glob or a path? Toss it in global if there's a global threshold: + if (thresholdGroups.indexOf(THRESHOLD_GROUP_TYPES.GLOBAL) > -1) { + groupTypeByThresholdGroup[THRESHOLD_GROUP_TYPES.GLOBAL] = + THRESHOLD_GROUP_TYPES.GLOBAL; + return files.concat([[file, THRESHOLD_GROUP_TYPES.GLOBAL]]); + } + + // A covered file that doesn't have a threshold: + return files.concat([[file, undefined]]); + }, + [] + ); + const getFilesInThresholdGroup = thresholdGroup => + coveredFilesSortedIntoThresholdGroup + .filter(fileAndGroup => fileAndGroup[1] === thresholdGroup) + .map(fileAndGroup => fileAndGroup[0]); + function combineCoverage(filePaths) { + return filePaths + .map(filePath => map.fileCoverageFor(filePath)) + .reduce((combinedCoverage, nextFileCoverage) => { + if (combinedCoverage === undefined || combinedCoverage === null) { + return nextFileCoverage.toSummary(); + } + return combinedCoverage.merge(nextFileCoverage.toSummary()); + }, undefined); + } + let errors = []; + thresholdGroups.forEach(thresholdGroup => { + switch (groupTypeByThresholdGroup[thresholdGroup]) { + case THRESHOLD_GROUP_TYPES.GLOBAL: { + const coverage = combineCoverage( + getFilesInThresholdGroup(THRESHOLD_GROUP_TYPES.GLOBAL) + ); + if (coverage) { + errors = errors.concat( + check( + thresholdGroup, + coverageThreshold[thresholdGroup], + coverage + ) + ); + } + break; + } + case THRESHOLD_GROUP_TYPES.PATH: { + const coverage = combineCoverage( + getFilesInThresholdGroup(thresholdGroup) + ); + if (coverage) { + errors = errors.concat( + check( + thresholdGroup, + coverageThreshold[thresholdGroup], + coverage + ) + ); + } + break; + } + case THRESHOLD_GROUP_TYPES.GLOB: + getFilesInThresholdGroup(thresholdGroup).forEach( + fileMatchingGlob => { + errors = errors.concat( + check( + fileMatchingGlob, + coverageThreshold[thresholdGroup], + map.fileCoverageFor(fileMatchingGlob).toSummary() + ) + ); + } + ); + break; + default: + // If the file specified by path is not found, error is returned. + if (thresholdGroup !== THRESHOLD_GROUP_TYPES.GLOBAL) { + errors = errors.concat( + `Jest: Coverage data for ${thresholdGroup} was not found.` + ); + } + // Sometimes all files in the coverage data are matched by + // PATH and GLOB threshold groups in which case, don't error when + // the global threshold group doesn't match any files. + } + }); + + errors = errors.filter( + err => err !== undefined && err !== null && err.length > 0 + ); + if (errors.length > 0) { + this.log(`${FAIL_COLOR(errors.join('\n'))}`); + this._setError(new Error(errors.join('\n'))); + } + } + } + async _getCoverageResult() { + if (this._globalConfig.coverageProvider === 'v8') { + const mergedCoverages = (0, _v8Coverage().mergeProcessCovs)( + this._v8CoverageResults.map(cov => ({ + result: cov.map(r => r.result) + })) + ); + const fileTransforms = new Map(); + this._v8CoverageResults.forEach(res => + res.forEach(r => { + if (r.codeTransformResult && !fileTransforms.has(r.result.url)) { + fileTransforms.set(r.result.url, r.codeTransformResult); + } + }) + ); + const transformedCoverage = await Promise.all( + mergedCoverages.result.map(async res => { + const fileTransform = fileTransforms.get(res.url); + let sourcemapContent = undefined; + if ( + fileTransform?.sourceMapPath && + fs().existsSync(fileTransform.sourceMapPath) + ) { + sourcemapContent = JSON.parse( + fs().readFileSync(fileTransform.sourceMapPath, 'utf8') + ); + } + const converter = (0, _v8ToIstanbul().default)( + res.url, + fileTransform?.wrapperLength ?? 0, + fileTransform && sourcemapContent + ? { + originalSource: fileTransform.originalCode, + source: fileTransform.code, + sourceMap: { + sourcemap: { + file: res.url, + ...sourcemapContent + } + } + } + : { + source: fs().readFileSync(res.url, 'utf8') + } + ); + await converter.load(); + converter.applyCoverage(res.functions); + const istanbulData = converter.toIstanbul(); + return istanbulData; + }) + ); + const map = _istanbulLibCoverage().default.createCoverageMap({}); + transformedCoverage.forEach(res => map.merge(res)); + const reportContext = _istanbulLibReport().default.createContext({ + coverageMap: map, + dir: this._globalConfig.coverageDirectory, + watermarks: (0, _getWatermarks.default)(this._globalConfig) + }); + return { + map, + reportContext + }; + } + const map = await this._sourceMapStore.transformCoverage(this._coverageMap); + const reportContext = _istanbulLibReport().default.createContext({ + coverageMap: map, + dir: this._globalConfig.coverageDirectory, + sourceFinder: this._sourceMapStore.sourceFinder, + watermarks: (0, _getWatermarks.default)(this._globalConfig) + }); + return { + map, + reportContext + }; + } +} +exports.default = CoverageReporter; diff --git a/node_modules/@jest/reporters/build/CoverageWorker.js b/node_modules/@jest/reporters/build/CoverageWorker.js new file mode 100644 index 0000000..1b9d652 --- /dev/null +++ b/node_modules/@jest/reporters/build/CoverageWorker.js @@ -0,0 +1,89 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.worker = worker; +function _exit() { + const data = _interopRequireDefault(require('exit')); + _exit = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +var _generateEmptyCoverage = _interopRequireDefault( + require('./generateEmptyCoverage') +); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Make sure uncaught errors are logged before we exit. +process.on('uncaughtException', err => { + console.error(err.stack); + (0, _exit().default)(1); +}); +function worker({config, globalConfig, path, context}) { + return (0, _generateEmptyCoverage.default)( + fs().readFileSync(path, 'utf8'), + path, + globalConfig, + config, + context.changedFiles && new Set(context.changedFiles), + context.sourcesRelatedToTestsInChangedFiles && + new Set(context.sourcesRelatedToTestsInChangedFiles) + ); +} diff --git a/node_modules/@jest/reporters/build/DefaultReporter.js b/node_modules/@jest/reporters/build/DefaultReporter.js new file mode 100644 index 0000000..4ebc37b --- /dev/null +++ b/node_modules/@jest/reporters/build/DefaultReporter.js @@ -0,0 +1,229 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _console() { + const data = require('@jest/console'); + _console = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _BaseReporter = _interopRequireDefault(require('./BaseReporter')); +var _Status = _interopRequireDefault(require('./Status')); +var _getResultHeader = _interopRequireDefault(require('./getResultHeader')); +var _getSnapshotStatus = _interopRequireDefault(require('./getSnapshotStatus')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const TITLE_BULLET = _chalk().default.bold('\u25cf '); +class DefaultReporter extends _BaseReporter.default { + _clear; // ANSI clear sequence for the last printed status + _err; + _globalConfig; + _out; + _status; + _bufferedOutput; + static filename = __filename; + constructor(globalConfig) { + super(); + this._globalConfig = globalConfig; + this._clear = ''; + this._out = process.stdout.write.bind(process.stdout); + this._err = process.stderr.write.bind(process.stderr); + this._status = new _Status.default(globalConfig); + this._bufferedOutput = new Set(); + this.__wrapStdio(process.stdout); + this.__wrapStdio(process.stderr); + this._status.onChange(() => { + this.__clearStatus(); + this.__printStatus(); + }); + } + __wrapStdio(stream) { + const write = stream.write.bind(stream); + let buffer = []; + let timeout = null; + const flushBufferedOutput = () => { + const string = buffer.join(''); + buffer = []; + + // This is to avoid conflicts between random output and status text + this.__clearStatus(); + if (string) { + write(string); + } + this.__printStatus(); + this._bufferedOutput.delete(flushBufferedOutput); + }; + this._bufferedOutput.add(flushBufferedOutput); + const debouncedFlush = () => { + // If the process blows up no errors would be printed. + // There should be a smart way to buffer stderr, but for now + // we just won't buffer it. + if (stream === process.stderr) { + flushBufferedOutput(); + } else { + if (!timeout) { + timeout = setTimeout(() => { + flushBufferedOutput(); + timeout = null; + }, 100); + } + } + }; + stream.write = chunk => { + buffer.push(chunk); + debouncedFlush(); + return true; + }; + } + + // Don't wait for the debounced call and flush all output immediately. + forceFlushBufferedOutput() { + for (const flushBufferedOutput of this._bufferedOutput) { + flushBufferedOutput(); + } + } + __clearStatus() { + if (_jestUtil().isInteractive) { + if (this._globalConfig.useStderr) { + this._err(this._clear); + } else { + this._out(this._clear); + } + } + } + __printStatus() { + const {content, clear} = this._status.get(); + this._clear = clear; + if (_jestUtil().isInteractive) { + if (this._globalConfig.useStderr) { + this._err(content); + } else { + this._out(content); + } + } + } + onRunStart(aggregatedResults, options) { + this._status.runStarted(aggregatedResults, options); + } + onTestStart(test) { + this._status.testStarted(test.path, test.context.config); + } + onTestCaseResult(test, testCaseResult) { + this._status.addTestCaseResult(test, testCaseResult); + } + onRunComplete() { + this.forceFlushBufferedOutput(); + this._status.runFinished(); + process.stdout.write = this._out; + process.stderr.write = this._err; + (0, _jestUtil().clearLine)(process.stderr); + } + onTestResult(test, testResult, aggregatedResults) { + this.testFinished(test.context.config, testResult, aggregatedResults); + if (!testResult.skipped) { + this.printTestFileHeader( + testResult.testFilePath, + test.context.config, + testResult + ); + this.printTestFileFailureMessage( + testResult.testFilePath, + test.context.config, + testResult + ); + } + this.forceFlushBufferedOutput(); + } + testFinished(config, testResult, aggregatedResults) { + this._status.testFinished(config, testResult, aggregatedResults); + } + printTestFileHeader(testPath, config, result) { + // log retry errors if any exist + result.testResults.forEach(testResult => { + const testRetryReasons = testResult.retryReasons; + if (testRetryReasons && testRetryReasons.length > 0) { + this.log( + `${_chalk().default.reset.inverse.bold.yellow( + ' LOGGING RETRY ERRORS ' + )} ${_chalk().default.bold(testResult.fullName)}` + ); + testRetryReasons.forEach((retryReasons, index) => { + let {message, stack} = (0, + _jestMessageUtil().separateMessageFromStack)(retryReasons); + stack = this._globalConfig.noStackTrace + ? '' + : _chalk().default.dim( + (0, _jestMessageUtil().formatStackTrace)( + stack, + config, + this._globalConfig, + testPath + ) + ); + message = (0, _jestMessageUtil().indentAllLines)(message); + this.log( + `${_chalk().default.reset.inverse.bold.blueBright( + ` RETRY ${index + 1} ` + )}\n` + ); + this.log(`${message}\n${stack}\n`); + }); + } + }); + this.log((0, _getResultHeader.default)(result, this._globalConfig, config)); + if (result.console) { + this.log( + ` ${TITLE_BULLET}Console\n\n${(0, _console().getConsoleOutput)( + result.console, + config, + this._globalConfig + )}` + ); + } + } + printTestFileFailureMessage(_testPath, _config, result) { + if (result.failureMessage) { + this.log(result.failureMessage); + } + const didUpdate = this._globalConfig.updateSnapshot === 'all'; + const snapshotStatuses = (0, _getSnapshotStatus.default)( + result.snapshot, + didUpdate + ); + snapshotStatuses.forEach(this.log); + } +} +exports.default = DefaultReporter; diff --git a/node_modules/@jest/reporters/build/GitHubActionsReporter.js b/node_modules/@jest/reporters/build/GitHubActionsReporter.js new file mode 100644 index 0000000..4fd9cf9 --- /dev/null +++ b/node_modules/@jest/reporters/build/GitHubActionsReporter.js @@ -0,0 +1,82 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _stripAnsi() { + const data = _interopRequireDefault(require('strip-ansi')); + _stripAnsi = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +var _BaseReporter = _interopRequireDefault(require('./BaseReporter')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const titleSeparator = ' \u203A '; +class GitHubActionsReporter extends _BaseReporter.default { + static filename = __filename; + onTestFileResult({context}, {testResults}) { + testResults.forEach(result => { + const title = [...result.ancestorTitles, result.title].join( + titleSeparator + ); + result.retryReasons?.forEach((retryReason, index) => { + this.#createAnnotation({ + ...this.#getMessageDetails(retryReason, context.config), + title: `RETRY ${index + 1}: ${title}`, + type: 'warning' + }); + }); + result.failureMessages.forEach(failureMessage => { + this.#createAnnotation({ + ...this.#getMessageDetails(failureMessage, context.config), + title, + type: 'error' + }); + }); + }); + } + #getMessageDetails(failureMessage, config) { + const {message, stack} = (0, _jestMessageUtil().separateMessageFromStack)( + failureMessage + ); + const stackLines = (0, _jestMessageUtil().getStackTraceLines)(stack); + const topFrame = (0, _jestMessageUtil().getTopFrame)(stackLines); + const normalizedStackLines = stackLines.map(line => + (0, _jestMessageUtil().formatPath)(line, config) + ); + const messageText = [message, ...normalizedStackLines].join('\n'); + return { + file: topFrame?.file, + line: topFrame?.line, + message: messageText + }; + } + #createAnnotation({file, line, message, title, type}) { + message = (0, _stripAnsi().default)( + // copied from: https://github.com/actions/toolkit/blob/main/packages/core/src/command.ts + message.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A') + ); + this.log( + `\n::${type} file=${file},line=${line},title=${title}::${message}` + ); + } +} +exports.default = GitHubActionsReporter; diff --git a/node_modules/@jest/reporters/build/NotifyReporter.js b/node_modules/@jest/reporters/build/NotifyReporter.js new file mode 100644 index 0000000..61352d7 --- /dev/null +++ b/node_modules/@jest/reporters/build/NotifyReporter.js @@ -0,0 +1,218 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function util() { + const data = _interopRequireWildcard(require('util')); + util = function () { + return data; + }; + return data; +} +function _exit() { + const data = _interopRequireDefault(require('exit')); + _exit = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _BaseReporter = _interopRequireDefault(require('./BaseReporter')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const isDarwin = process.platform === 'darwin'; +const icon = path().resolve(__dirname, '../assets/jest_logo.png'); +class NotifyReporter extends _BaseReporter.default { + _notifier = loadNotifier(); + _globalConfig; + _context; + static filename = __filename; + constructor(globalConfig, context) { + super(); + this._globalConfig = globalConfig; + this._context = context; + } + onRunComplete(testContexts, result) { + const success = + result.numFailedTests === 0 && result.numRuntimeErrorTestSuites === 0; + const firstContext = testContexts.values().next(); + const hasteFS = + firstContext && firstContext.value && firstContext.value.hasteFS; + let packageName; + if (hasteFS != null) { + // assuming root package.json is the first one + const [filePath] = hasteFS.matchFiles('package.json'); + packageName = + filePath != null + ? hasteFS.getModuleName(filePath) + : this._globalConfig.rootDir; + } else { + packageName = this._globalConfig.rootDir; + } + packageName = packageName != null ? `${packageName} - ` : ''; + const notifyMode = this._globalConfig.notifyMode; + const statusChanged = + this._context.previousSuccess !== success || this._context.firstRun; + const testsHaveRun = result.numTotalTests !== 0; + if ( + testsHaveRun && + success && + (notifyMode === 'always' || + notifyMode === 'success' || + notifyMode === 'success-change' || + (notifyMode === 'change' && statusChanged) || + (notifyMode === 'failure-change' && statusChanged)) + ) { + const title = util().format('%s%d%% Passed', packageName, 100); + const message = `${isDarwin ? '\u2705 ' : ''}${(0, _jestUtil().pluralize)( + 'test', + result.numPassedTests + )} passed`; + this._notifier.notify({ + hint: 'int:transient:1', + icon, + message, + timeout: false, + title + }); + } else if ( + testsHaveRun && + !success && + (notifyMode === 'always' || + notifyMode === 'failure' || + notifyMode === 'failure-change' || + (notifyMode === 'change' && statusChanged) || + (notifyMode === 'success-change' && statusChanged)) + ) { + const failed = result.numFailedTests / result.numTotalTests; + const title = util().format( + '%s%d%% Failed', + packageName, + Math.ceil(Number.isNaN(failed) ? 0 : failed * 100) + ); + const message = util().format( + `${isDarwin ? '\u26D4\uFE0F ' : ''}%d of %d tests failed`, + result.numFailedTests, + result.numTotalTests + ); + const watchMode = this._globalConfig.watch || this._globalConfig.watchAll; + const restartAnswer = 'Run again'; + const quitAnswer = 'Exit tests'; + if (!watchMode) { + this._notifier.notify({ + hint: 'int:transient:1', + icon, + message, + timeout: false, + title + }); + } else { + this._notifier.notify( + { + // @ts-expect-error - not all options are supported by all systems (specifically `actions` and `hint`) + actions: [restartAnswer, quitAnswer], + closeLabel: 'Close', + hint: 'int:transient:1', + icon, + message, + timeout: false, + title + }, + (err, _, metadata) => { + if (err || !metadata) { + return; + } + if (metadata.activationValue === quitAnswer) { + (0, _exit().default)(0); + return; + } + if ( + metadata.activationValue === restartAnswer && + this._context.startRun + ) { + this._context.startRun(this._globalConfig); + } + } + ); + } + } + this._context.previousSuccess = success; + this._context.firstRun = false; + } +} +exports.default = NotifyReporter; +function loadNotifier() { + try { + return require('node-notifier'); + } catch (err) { + if (err.code !== 'MODULE_NOT_FOUND') { + throw err; + } + throw Error( + 'notify reporter requires optional peer dependency "node-notifier" but it was not found' + ); + } +} diff --git a/node_modules/@jest/reporters/build/Status.js b/node_modules/@jest/reporters/build/Status.js new file mode 100644 index 0000000..d2d1eaa --- /dev/null +++ b/node_modules/@jest/reporters/build/Status.js @@ -0,0 +1,214 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _stringLength() { + const data = _interopRequireDefault(require('string-length')); + _stringLength = function () { + return data; + }; + return data; +} +var _getSummary = _interopRequireDefault(require('./getSummary')); +var _printDisplayName = _interopRequireDefault(require('./printDisplayName')); +var _trimAndFormatPath = _interopRequireDefault(require('./trimAndFormatPath')); +var _wrapAnsiString = _interopRequireDefault(require('./wrapAnsiString')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const RUNNING_TEXT = ' RUNS '; +const RUNNING = `${_chalk().default.reset.inverse.yellow.bold(RUNNING_TEXT)} `; + +/** + * This class is a perf optimization for sorting the list of currently + * running tests. It tries to keep tests in the same positions without + * shifting the whole list. + */ +class CurrentTestList { + _array; + constructor() { + this._array = []; + } + add(testPath, config) { + const index = this._array.indexOf(null); + const record = { + config, + testPath + }; + if (index !== -1) { + this._array[index] = record; + } else { + this._array.push(record); + } + } + delete(testPath) { + const record = this._array.find( + record => record !== null && record.testPath === testPath + ); + this._array[this._array.indexOf(record || null)] = null; + } + get() { + return this._array; + } +} +/** + * A class that generates the CLI status of currently running tests + * and also provides an ANSI escape sequence to remove status lines + * from the terminal. + */ +class Status { + _cache; + _callback; + _currentTests; + _currentTestCases; + _done; + _emitScheduled; + _estimatedTime; + _interval; + _aggregatedResults; + _showStatus; + constructor(_globalConfig) { + this._globalConfig = _globalConfig; + this._cache = null; + this._currentTests = new CurrentTestList(); + this._currentTestCases = []; + this._done = false; + this._emitScheduled = false; + this._estimatedTime = 0; + this._showStatus = false; + } + onChange(callback) { + this._callback = callback; + } + runStarted(aggregatedResults, options) { + this._estimatedTime = (options && options.estimatedTime) || 0; + this._showStatus = options && options.showStatus; + this._interval = setInterval(() => this._tick(), 1000); + this._aggregatedResults = aggregatedResults; + this._debouncedEmit(); + } + runFinished() { + this._done = true; + if (this._interval) clearInterval(this._interval); + this._emit(); + } + addTestCaseResult(test, testCaseResult) { + this._currentTestCases.push({ + test, + testCaseResult + }); + if (!this._showStatus) { + this._emit(); + } else { + this._debouncedEmit(); + } + } + testStarted(testPath, config) { + this._currentTests.add(testPath, config); + if (!this._showStatus) { + this._emit(); + } else { + this._debouncedEmit(); + } + } + testFinished(_config, testResult, aggregatedResults) { + const {testFilePath} = testResult; + this._aggregatedResults = aggregatedResults; + this._currentTests.delete(testFilePath); + this._currentTestCases = this._currentTestCases.filter(({test}) => { + if (_config !== test.context.config) { + return true; + } + return test.path !== testFilePath; + }); + this._debouncedEmit(); + } + get() { + if (this._cache) { + return this._cache; + } + if (this._done) { + return { + clear: '', + content: '' + }; + } + const width = process.stdout.columns; + let content = '\n'; + this._currentTests.get().forEach(record => { + if (record) { + const {config, testPath} = record; + const projectDisplayName = config.displayName + ? `${(0, _printDisplayName.default)(config)} ` + : ''; + const prefix = RUNNING + projectDisplayName; + content += `${(0, _wrapAnsiString.default)( + prefix + + (0, _trimAndFormatPath.default)( + (0, _stringLength().default)(prefix), + config, + testPath, + width + ), + width + )}\n`; + } + }); + if (this._showStatus && this._aggregatedResults) { + content += `\n${(0, _getSummary.default)(this._aggregatedResults, { + currentTestCases: this._currentTestCases, + estimatedTime: this._estimatedTime, + roundTime: true, + seed: this._globalConfig.seed, + showSeed: this._globalConfig.showSeed, + width + })}`; + } + let height = 0; + for (let i = 0; i < content.length; i++) { + if (content[i] === '\n') { + height++; + } + } + const clear = '\r\x1B[K\r\x1B[1A'.repeat(height); + return (this._cache = { + clear, + content + }); + } + _emit() { + this._cache = null; + if (this._callback) this._callback(); + } + _debouncedEmit() { + if (!this._emitScheduled) { + // Perf optimization to avoid two separate renders When + // one test finishes and another test starts executing. + this._emitScheduled = true; + setTimeout(() => { + this._emit(); + this._emitScheduled = false; + }, 100); + } + } + _tick() { + this._debouncedEmit(); + } +} +exports.default = Status; diff --git a/node_modules/@jest/reporters/build/SummaryReporter.js b/node_modules/@jest/reporters/build/SummaryReporter.js new file mode 100644 index 0000000..59cd6fc --- /dev/null +++ b/node_modules/@jest/reporters/build/SummaryReporter.js @@ -0,0 +1,231 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _BaseReporter = _interopRequireDefault(require('./BaseReporter')); +var _getResultHeader = _interopRequireDefault(require('./getResultHeader')); +var _getSnapshotSummary = _interopRequireDefault( + require('./getSnapshotSummary') +); +var _getSummary = _interopRequireDefault(require('./getSummary')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const TEST_SUMMARY_THRESHOLD = 20; +const NPM_EVENTS = new Set([ + 'prepublish', + 'publish', + 'postpublish', + 'preinstall', + 'install', + 'postinstall', + 'preuninstall', + 'uninstall', + 'postuninstall', + 'preversion', + 'version', + 'postversion', + 'pretest', + 'test', + 'posttest', + 'prestop', + 'stop', + 'poststop', + 'prestart', + 'start', + 'poststart', + 'prerestart', + 'restart', + 'postrestart' +]); +const {npm_config_user_agent, npm_lifecycle_event, npm_lifecycle_script} = + process.env; +class SummaryReporter extends _BaseReporter.default { + _estimatedTime; + _globalConfig; + static filename = __filename; + constructor(globalConfig) { + super(); + this._globalConfig = globalConfig; + this._estimatedTime = 0; + } + + // If we write more than one character at a time it is possible that + // Node.js exits in the middle of printing the result. This was first observed + // in Node.js 0.10 and still persists in Node.js 6.7+. + // Let's print the test failure summary character by character which is safer + // when hundreds of tests are failing. + _write(string) { + for (let i = 0; i < string.length; i++) { + process.stderr.write(string.charAt(i)); + } + } + onRunStart(aggregatedResults, options) { + super.onRunStart(aggregatedResults, options); + this._estimatedTime = options.estimatedTime; + } + onRunComplete(testContexts, aggregatedResults) { + const {numTotalTestSuites, testResults, wasInterrupted} = aggregatedResults; + if (numTotalTestSuites) { + const lastResult = testResults[testResults.length - 1]; + // Print a newline if the last test did not fail to line up newlines + // similar to when an error would have been thrown in the test. + if ( + !this._globalConfig.verbose && + lastResult && + !lastResult.numFailingTests && + !lastResult.testExecError + ) { + this.log(''); + } + this._printSummary(aggregatedResults, this._globalConfig); + this._printSnapshotSummary( + aggregatedResults.snapshot, + this._globalConfig + ); + if (numTotalTestSuites) { + let message = (0, _getSummary.default)(aggregatedResults, { + estimatedTime: this._estimatedTime, + seed: this._globalConfig.seed, + showSeed: this._globalConfig.showSeed + }); + if (!this._globalConfig.silent) { + message += `\n${ + wasInterrupted + ? _chalk().default.bold.red('Test run was interrupted.') + : this._getTestSummary(testContexts, this._globalConfig) + }`; + } + this.log(message); + } + } + } + _printSnapshotSummary(snapshots, globalConfig) { + if ( + snapshots.added || + snapshots.filesRemoved || + snapshots.unchecked || + snapshots.unmatched || + snapshots.updated + ) { + let updateCommand; + const event = npm_lifecycle_event || ''; + const prefix = NPM_EVENTS.has(event) ? '' : 'run '; + const isYarn = + typeof npm_config_user_agent === 'string' && + npm_config_user_agent.includes('yarn'); + const client = isYarn ? 'yarn' : 'npm'; + const scriptUsesJest = + typeof npm_lifecycle_script === 'string' && + npm_lifecycle_script.includes('jest'); + if (globalConfig.watch || globalConfig.watchAll) { + updateCommand = 'press `u`'; + } else if (event && scriptUsesJest) { + updateCommand = `run \`${`${client} ${prefix}${event}${ + isYarn ? '' : ' --' + }`} -u\``; + } else { + updateCommand = 're-run jest with `-u`'; + } + const snapshotSummary = (0, _getSnapshotSummary.default)( + snapshots, + globalConfig, + updateCommand + ); + snapshotSummary.forEach(this.log); + this.log(''); // print empty line + } + } + + _printSummary(aggregatedResults, globalConfig) { + // If there were any failing tests and there was a large number of tests + // executed, re-print the failing results at the end of execution output. + const failedTests = aggregatedResults.numFailedTests; + const runtimeErrors = aggregatedResults.numRuntimeErrorTestSuites; + if ( + failedTests + runtimeErrors > 0 && + aggregatedResults.numTotalTestSuites > TEST_SUMMARY_THRESHOLD + ) { + this.log(_chalk().default.bold('Summary of all failing tests')); + aggregatedResults.testResults.forEach(testResult => { + const {failureMessage} = testResult; + if (failureMessage) { + this._write( + `${(0, _getResultHeader.default)( + testResult, + globalConfig + )}\n${failureMessage}\n` + ); + } + }); + this.log(''); // print empty line + } + } + + _getTestSummary(testContexts, globalConfig) { + const getMatchingTestsInfo = () => { + const prefix = globalConfig.findRelatedTests + ? ' related to files matching ' + : ' matching '; + return ( + _chalk().default.dim(prefix) + + (0, _jestUtil().testPathPatternToRegExp)( + globalConfig.testPathPattern + ).toString() + ); + }; + let testInfo = ''; + if (globalConfig.runTestsByPath) { + testInfo = _chalk().default.dim(' within paths'); + } else if (globalConfig.onlyChanged) { + testInfo = _chalk().default.dim(' related to changed files'); + } else if (globalConfig.testPathPattern) { + testInfo = getMatchingTestsInfo(); + } + let nameInfo = ''; + if (globalConfig.runTestsByPath) { + nameInfo = ` ${globalConfig.nonFlagArgs.map(p => `"${p}"`).join(', ')}`; + } else if (globalConfig.testNamePattern) { + nameInfo = `${_chalk().default.dim(' with tests matching ')}"${ + globalConfig.testNamePattern + }"`; + } + const contextInfo = + testContexts.size > 1 + ? _chalk().default.dim(' in ') + + testContexts.size + + _chalk().default.dim(' projects') + : ''; + return ( + _chalk().default.dim('Ran all test suites') + + testInfo + + nameInfo + + contextInfo + + _chalk().default.dim('.') + ); + } +} +exports.default = SummaryReporter; diff --git a/node_modules/@jest/reporters/build/VerboseReporter.js b/node_modules/@jest/reporters/build/VerboseReporter.js new file mode 100644 index 0000000..6380378 --- /dev/null +++ b/node_modules/@jest/reporters/build/VerboseReporter.js @@ -0,0 +1,175 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _DefaultReporter = _interopRequireDefault(require('./DefaultReporter')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const {ICONS} = _jestUtil().specialChars; +class VerboseReporter extends _DefaultReporter.default { + _globalConfig; + static filename = __filename; + constructor(globalConfig) { + super(globalConfig); + this._globalConfig = globalConfig; + } + + // Verbose mode is for debugging. Buffering of output is undesirable. + // See https://github.com/facebook/jest/issues/8208 + __wrapStdio(stream) { + const write = stream.write.bind(stream); + stream.write = chunk => { + this.__clearStatus(); + write(chunk); + this.__printStatus(); + return true; + }; + } + static filterTestResults(testResults) { + return testResults.filter(({status}) => status !== 'pending'); + } + static groupTestsBySuites(testResults) { + const root = { + suites: [], + tests: [], + title: '' + }; + testResults.forEach(testResult => { + let targetSuite = root; + + // Find the target suite for this test, + // creating nested suites as necessary. + for (const title of testResult.ancestorTitles) { + let matchingSuite = targetSuite.suites.find(s => s.title === title); + if (!matchingSuite) { + matchingSuite = { + suites: [], + tests: [], + title + }; + targetSuite.suites.push(matchingSuite); + } + targetSuite = matchingSuite; + } + targetSuite.tests.push(testResult); + }); + return root; + } + onTestResult(test, result, aggregatedResults) { + super.testFinished(test.context.config, result, aggregatedResults); + if (!result.skipped) { + this.printTestFileHeader( + result.testFilePath, + test.context.config, + result + ); + if (!result.testExecError && !result.skipped) { + this._logTestResults(result.testResults); + } + this.printTestFileFailureMessage( + result.testFilePath, + test.context.config, + result + ); + } + super.forceFlushBufferedOutput(); + } + _logTestResults(testResults) { + this._logSuite(VerboseReporter.groupTestsBySuites(testResults), 0); + this._logLine(); + } + _logSuite(suite, indentLevel) { + if (suite.title) { + this._logLine(suite.title, indentLevel); + } + this._logTests(suite.tests, indentLevel + 1); + suite.suites.forEach(suite => this._logSuite(suite, indentLevel + 1)); + } + _getIcon(status) { + if (status === 'failed') { + return _chalk().default.red(ICONS.failed); + } else if (status === 'pending') { + return _chalk().default.yellow(ICONS.pending); + } else if (status === 'todo') { + return _chalk().default.magenta(ICONS.todo); + } else { + return _chalk().default.green(ICONS.success); + } + } + _logTest(test, indentLevel) { + const status = this._getIcon(test.status); + const time = test.duration + ? ` (${(0, _jestUtil().formatTime)(Math.round(test.duration))})` + : ''; + this._logLine( + `${status} ${_chalk().default.dim(test.title + time)}`, + indentLevel + ); + } + _logTests(tests, indentLevel) { + if (this._globalConfig.expand) { + tests.forEach(test => this._logTest(test, indentLevel)); + } else { + const summedTests = tests.reduce( + (result, test) => { + if (test.status === 'pending') { + result.pending.push(test); + } else if (test.status === 'todo') { + result.todo.push(test); + } else { + this._logTest(test, indentLevel); + } + return result; + }, + { + pending: [], + todo: [] + } + ); + if (summedTests.pending.length > 0) { + summedTests.pending.forEach(this._logTodoOrPendingTest(indentLevel)); + } + if (summedTests.todo.length > 0) { + summedTests.todo.forEach(this._logTodoOrPendingTest(indentLevel)); + } + } + } + _logTodoOrPendingTest(indentLevel) { + return test => { + const printedTestStatus = + test.status === 'pending' ? 'skipped' : test.status; + const icon = this._getIcon(test.status); + const text = _chalk().default.dim(`${printedTestStatus} ${test.title}`); + this._logLine(`${icon} ${text}`, indentLevel); + }; + } + _logLine(str, indentLevel) { + const indentation = ' '.repeat(indentLevel || 0); + this.log(indentation + (str || '')); + } +} +exports.default = VerboseReporter; diff --git a/node_modules/@jest/reporters/build/formatTestPath.js b/node_modules/@jest/reporters/build/formatTestPath.js new file mode 100644 index 0000000..8b8894b --- /dev/null +++ b/node_modules/@jest/reporters/build/formatTestPath.js @@ -0,0 +1,84 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = formatTestPath; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _slash() { + const data = _interopRequireDefault(require('slash')); + _slash = function () { + return data; + }; + return data; +} +var _relativePath = _interopRequireDefault(require('./relativePath')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function formatTestPath(config, testPath) { + const {dirname, basename} = (0, _relativePath.default)(config, testPath); + return (0, _slash().default)( + _chalk().default.dim(dirname + path().sep) + _chalk().default.bold(basename) + ); +} diff --git a/node_modules/@jest/reporters/build/generateEmptyCoverage.js b/node_modules/@jest/reporters/build/generateEmptyCoverage.js new file mode 100644 index 0000000..7f3f119 --- /dev/null +++ b/node_modules/@jest/reporters/build/generateEmptyCoverage.js @@ -0,0 +1,151 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = generateEmptyCoverage; +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _istanbulLibCoverage() { + const data = require('istanbul-lib-coverage'); + _istanbulLibCoverage = function () { + return data; + }; + return data; +} +function _istanbulLibInstrument() { + const data = require('istanbul-lib-instrument'); + _istanbulLibInstrument = function () { + return data; + }; + return data; +} +function _transform() { + const data = require('@jest/transform'); + _transform = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +async function generateEmptyCoverage( + source, + filename, + globalConfig, + config, + changedFiles, + sourcesRelatedToTestsInChangedFiles +) { + const coverageOptions = { + changedFiles, + collectCoverage: globalConfig.collectCoverage, + collectCoverageFrom: globalConfig.collectCoverageFrom, + coverageProvider: globalConfig.coverageProvider, + sourcesRelatedToTestsInChangedFiles + }; + let coverageWorkerResult = null; + if ((0, _transform().shouldInstrument)(filename, coverageOptions, config)) { + if (coverageOptions.coverageProvider === 'v8') { + const stat = fs().statSync(filename); + return { + kind: 'V8Coverage', + result: { + functions: [ + { + functionName: '(empty-report)', + isBlockCoverage: true, + ranges: [ + { + count: 0, + endOffset: stat.size, + startOffset: 0 + } + ] + } + ], + scriptId: '0', + url: filename + } + }; + } + const scriptTransformer = await (0, _transform().createScriptTransformer)( + config + ); + + // Transform file with instrumentation to make sure initial coverage data is well mapped to original code. + const {code} = await scriptTransformer.transformSourceAsync( + filename, + source, + { + instrument: true, + supportsDynamicImport: true, + supportsExportNamespaceFrom: true, + supportsStaticESM: true, + supportsTopLevelAwait: true + } + ); + // TODO: consider passing AST + const extracted = (0, _istanbulLibInstrument().readInitialCoverage)(code); + // Check extracted initial coverage is not null, this can happen when using /* istanbul ignore file */ + if (extracted) { + coverageWorkerResult = { + coverage: (0, _istanbulLibCoverage().createFileCoverage)( + extracted.coverageData + ), + kind: 'BabelCoverage' + }; + } + } + return coverageWorkerResult; +} diff --git a/node_modules/@jest/reporters/build/getResultHeader.js b/node_modules/@jest/reporters/build/getResultHeader.js new file mode 100644 index 0000000..5fc9757 --- /dev/null +++ b/node_modules/@jest/reporters/build/getResultHeader.js @@ -0,0 +1,65 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getResultHeader; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _formatTestPath = _interopRequireDefault(require('./formatTestPath')); +var _printDisplayName = _interopRequireDefault(require('./printDisplayName')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const LONG_TEST_COLOR = _chalk().default.reset.bold.bgRed; +// Explicitly reset for these messages since they can get written out in the +// middle of error logging +const FAIL_TEXT = 'FAIL'; +const PASS_TEXT = 'PASS'; +const FAIL = _chalk().default.supportsColor + ? _chalk().default.reset.inverse.bold.red(` ${FAIL_TEXT} `) + : FAIL_TEXT; +const PASS = _chalk().default.supportsColor + ? _chalk().default.reset.inverse.bold.green(` ${PASS_TEXT} `) + : PASS_TEXT; +function getResultHeader(result, globalConfig, projectConfig) { + const testPath = result.testFilePath; + const status = + result.numFailingTests > 0 || result.testExecError ? FAIL : PASS; + const testDetail = []; + if (result.perfStats?.slow) { + const runTime = result.perfStats.runtime / 1000; + testDetail.push(LONG_TEST_COLOR((0, _jestUtil().formatTime)(runTime, 0))); + } + if (result.memoryUsage) { + const toMB = bytes => Math.floor(bytes / 1024 / 1024); + testDetail.push(`${toMB(result.memoryUsage)} MB heap size`); + } + const projectDisplayName = + projectConfig && projectConfig.displayName + ? `${(0, _printDisplayName.default)(projectConfig)} ` + : ''; + return `${status} ${projectDisplayName}${(0, _formatTestPath.default)( + projectConfig ?? globalConfig, + testPath + )}${testDetail.length ? ` (${testDetail.join(', ')})` : ''}`; +} diff --git a/node_modules/@jest/reporters/build/getSnapshotStatus.js b/node_modules/@jest/reporters/build/getSnapshotStatus.js new file mode 100644 index 0000000..0006247 --- /dev/null +++ b/node_modules/@jest/reporters/build/getSnapshotStatus.js @@ -0,0 +1,92 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getSnapshotStatus; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const ARROW = ' \u203A '; +const DOT = ' \u2022 '; +const FAIL_COLOR = _chalk().default.bold.red; +const SNAPSHOT_ADDED = _chalk().default.bold.green; +const SNAPSHOT_UPDATED = _chalk().default.bold.green; +const SNAPSHOT_OUTDATED = _chalk().default.bold.yellow; +function getSnapshotStatus(snapshot, afterUpdate) { + const statuses = []; + if (snapshot.added) { + statuses.push( + SNAPSHOT_ADDED( + `${ + ARROW + (0, _jestUtil().pluralize)('snapshot', snapshot.added) + } written.` + ) + ); + } + if (snapshot.updated) { + statuses.push( + SNAPSHOT_UPDATED( + `${ + ARROW + (0, _jestUtil().pluralize)('snapshot', snapshot.updated) + } updated.` + ) + ); + } + if (snapshot.unmatched) { + statuses.push( + FAIL_COLOR( + `${ + ARROW + (0, _jestUtil().pluralize)('snapshot', snapshot.unmatched) + } failed.` + ) + ); + } + if (snapshot.unchecked) { + if (afterUpdate) { + statuses.push( + SNAPSHOT_UPDATED( + `${ + ARROW + (0, _jestUtil().pluralize)('snapshot', snapshot.unchecked) + } removed.` + ) + ); + } else { + statuses.push( + `${SNAPSHOT_OUTDATED( + `${ + ARROW + (0, _jestUtil().pluralize)('snapshot', snapshot.unchecked) + } obsolete` + )}.` + ); + } + snapshot.uncheckedKeys.forEach(key => { + statuses.push(` ${DOT}${key}`); + }); + } + if (snapshot.fileDeleted) { + statuses.push(SNAPSHOT_UPDATED(`${ARROW}snapshot file removed.`)); + } + return statuses; +} diff --git a/node_modules/@jest/reporters/build/getSnapshotSummary.js b/node_modules/@jest/reporters/build/getSnapshotSummary.js new file mode 100644 index 0000000..0312e27 --- /dev/null +++ b/node_modules/@jest/reporters/build/getSnapshotSummary.js @@ -0,0 +1,169 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getSnapshotSummary; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _formatTestPath = _interopRequireDefault(require('./formatTestPath')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const ARROW = ' \u203A '; +const DOWN_ARROW = ' \u21B3 '; +const DOT = ' \u2022 '; +const FAIL_COLOR = _chalk().default.bold.red; +const OBSOLETE_COLOR = _chalk().default.bold.yellow; +const SNAPSHOT_ADDED = _chalk().default.bold.green; +const SNAPSHOT_NOTE = _chalk().default.dim; +const SNAPSHOT_REMOVED = _chalk().default.bold.green; +const SNAPSHOT_SUMMARY = _chalk().default.bold; +const SNAPSHOT_UPDATED = _chalk().default.bold.green; +function getSnapshotSummary(snapshots, globalConfig, updateCommand) { + const summary = []; + summary.push(SNAPSHOT_SUMMARY('Snapshot Summary')); + if (snapshots.added) { + summary.push( + `${SNAPSHOT_ADDED( + `${ + ARROW + (0, _jestUtil().pluralize)('snapshot', snapshots.added) + } written ` + )}from ${(0, _jestUtil().pluralize)('test suite', snapshots.filesAdded)}.` + ); + } + if (snapshots.unmatched) { + summary.push( + `${FAIL_COLOR( + `${ARROW}${(0, _jestUtil().pluralize)( + 'snapshot', + snapshots.unmatched + )} failed` + )} from ${(0, _jestUtil().pluralize)( + 'test suite', + snapshots.filesUnmatched + )}. ${SNAPSHOT_NOTE( + `Inspect your code changes or ${updateCommand} to update them.` + )}` + ); + } + if (snapshots.updated) { + summary.push( + `${SNAPSHOT_UPDATED( + `${ + ARROW + (0, _jestUtil().pluralize)('snapshot', snapshots.updated) + } updated ` + )}from ${(0, _jestUtil().pluralize)( + 'test suite', + snapshots.filesUpdated + )}.` + ); + } + if (snapshots.filesRemoved) { + if (snapshots.didUpdate) { + summary.push( + `${SNAPSHOT_REMOVED( + `${ARROW}${(0, _jestUtil().pluralize)( + 'snapshot file', + snapshots.filesRemoved + )} removed ` + )}from ${(0, _jestUtil().pluralize)( + 'test suite', + snapshots.filesRemoved + )}.` + ); + } else { + summary.push( + `${OBSOLETE_COLOR( + `${ARROW}${(0, _jestUtil().pluralize)( + 'snapshot file', + snapshots.filesRemoved + )} obsolete ` + )}from ${(0, _jestUtil().pluralize)( + 'test suite', + snapshots.filesRemoved + )}. ${SNAPSHOT_NOTE( + `To remove ${ + snapshots.filesRemoved === 1 ? 'it' : 'them all' + }, ${updateCommand}.` + )}` + ); + } + } + if (snapshots.filesRemovedList && snapshots.filesRemovedList.length) { + const [head, ...tail] = snapshots.filesRemovedList; + summary.push( + ` ${DOWN_ARROW} ${DOT}${(0, _formatTestPath.default)( + globalConfig, + head + )}` + ); + tail.forEach(key => { + summary.push( + ` ${DOT}${(0, _formatTestPath.default)(globalConfig, key)}` + ); + }); + } + if (snapshots.unchecked) { + if (snapshots.didUpdate) { + summary.push( + `${SNAPSHOT_REMOVED( + `${ARROW}${(0, _jestUtil().pluralize)( + 'snapshot', + snapshots.unchecked + )} removed ` + )}from ${(0, _jestUtil().pluralize)( + 'test suite', + snapshots.uncheckedKeysByFile.length + )}.` + ); + } else { + summary.push( + `${OBSOLETE_COLOR( + `${ARROW}${(0, _jestUtil().pluralize)( + 'snapshot', + snapshots.unchecked + )} obsolete ` + )}from ${(0, _jestUtil().pluralize)( + 'test suite', + snapshots.uncheckedKeysByFile.length + )}. ${SNAPSHOT_NOTE( + `To remove ${ + snapshots.unchecked === 1 ? 'it' : 'them all' + }, ${updateCommand}.` + )}` + ); + } + snapshots.uncheckedKeysByFile.forEach(uncheckedFile => { + summary.push( + ` ${DOWN_ARROW}${(0, _formatTestPath.default)( + globalConfig, + uncheckedFile.filePath + )}` + ); + uncheckedFile.keys.forEach(key => { + summary.push(` ${DOT}${key}`); + }); + }); + } + return summary; +} diff --git a/node_modules/@jest/reporters/build/getSummary.js b/node_modules/@jest/reporters/build/getSummary.js new file mode 100644 index 0000000..4d74283 --- /dev/null +++ b/node_modules/@jest/reporters/build/getSummary.js @@ -0,0 +1,206 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.PROGRESS_BAR_WIDTH = void 0; +exports.default = getSummary; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const PROGRESS_BAR_WIDTH = 40; +exports.PROGRESS_BAR_WIDTH = PROGRESS_BAR_WIDTH; +function getValuesCurrentTestCases(currentTestCases = []) { + let numFailingTests = 0; + let numPassingTests = 0; + let numPendingTests = 0; + let numTodoTests = 0; + let numTotalTests = 0; + currentTestCases.forEach(testCase => { + switch (testCase.testCaseResult.status) { + case 'failed': { + numFailingTests++; + break; + } + case 'passed': { + numPassingTests++; + break; + } + case 'skipped': { + numPendingTests++; + break; + } + case 'todo': { + numTodoTests++; + break; + } + } + numTotalTests++; + }); + return { + numFailingTests, + numPassingTests, + numPendingTests, + numTodoTests, + numTotalTests + }; +} +function renderTime(runTime, estimatedTime, width) { + // If we are more than one second over the estimated time, highlight it. + const renderedTime = + estimatedTime && runTime >= estimatedTime + 1 + ? _chalk().default.bold.yellow((0, _jestUtil().formatTime)(runTime, 0)) + : (0, _jestUtil().formatTime)(runTime, 0); + let time = `${_chalk().default.bold('Time:')} ${renderedTime}`; + if (runTime < estimatedTime) { + time += `, estimated ${(0, _jestUtil().formatTime)(estimatedTime, 0)}`; + } + + // Only show a progress bar if the test run is actually going to take + // some time. + if (estimatedTime > 2 && runTime < estimatedTime && width) { + const availableWidth = Math.min(PROGRESS_BAR_WIDTH, width); + const length = Math.min( + Math.floor((runTime / estimatedTime) * availableWidth), + availableWidth + ); + if (availableWidth >= 2) { + time += `\n${_chalk().default.green('█').repeat(length)}${_chalk() + .default.white('█') + .repeat(availableWidth - length)}`; + } + } + return time; +} +function getSummary(aggregatedResults, options) { + let runTime = (Date.now() - aggregatedResults.startTime) / 1000; + if (options && options.roundTime) { + runTime = Math.floor(runTime); + } + const valuesForCurrentTestCases = getValuesCurrentTestCases( + options?.currentTestCases + ); + const estimatedTime = (options && options.estimatedTime) || 0; + const snapshotResults = aggregatedResults.snapshot; + const snapshotsAdded = snapshotResults.added; + const snapshotsFailed = snapshotResults.unmatched; + const snapshotsOutdated = snapshotResults.unchecked; + const snapshotsFilesRemoved = snapshotResults.filesRemoved; + const snapshotsDidUpdate = snapshotResults.didUpdate; + const snapshotsPassed = snapshotResults.matched; + const snapshotsTotal = snapshotResults.total; + const snapshotsUpdated = snapshotResults.updated; + const suitesFailed = aggregatedResults.numFailedTestSuites; + const suitesPassed = aggregatedResults.numPassedTestSuites; + const suitesPending = aggregatedResults.numPendingTestSuites; + const suitesRun = suitesFailed + suitesPassed; + const suitesTotal = aggregatedResults.numTotalTestSuites; + const testsFailed = aggregatedResults.numFailedTests; + const testsPassed = aggregatedResults.numPassedTests; + const testsPending = aggregatedResults.numPendingTests; + const testsTodo = aggregatedResults.numTodoTests; + const testsTotal = aggregatedResults.numTotalTests; + const width = (options && options.width) || 0; + const optionalLines = []; + if (options?.showSeed === true) { + const {seed} = options; + if (seed === undefined) { + throw new Error('Attempted to display seed but seed value is undefined'); + } + optionalLines.push(`${_chalk().default.bold('Seed: ') + seed}`); + } + const suites = `${ + _chalk().default.bold('Test Suites: ') + + (suitesFailed + ? `${_chalk().default.bold.red(`${suitesFailed} failed`)}, ` + : '') + + (suitesPending + ? `${_chalk().default.bold.yellow(`${suitesPending} skipped`)}, ` + : '') + + (suitesPassed + ? `${_chalk().default.bold.green(`${suitesPassed} passed`)}, ` + : '') + + (suitesRun !== suitesTotal ? `${suitesRun} of ${suitesTotal}` : suitesTotal) + } total`; + const updatedTestsFailed = + testsFailed + valuesForCurrentTestCases.numFailingTests; + const updatedTestsPending = + testsPending + valuesForCurrentTestCases.numPendingTests; + const updatedTestsTodo = testsTodo + valuesForCurrentTestCases.numTodoTests; + const updatedTestsPassed = + testsPassed + valuesForCurrentTestCases.numPassingTests; + const updatedTestsTotal = + testsTotal + valuesForCurrentTestCases.numTotalTests; + const tests = `${ + _chalk().default.bold('Tests: ') + + (updatedTestsFailed > 0 + ? `${_chalk().default.bold.red(`${updatedTestsFailed} failed`)}, ` + : '') + + (updatedTestsPending > 0 + ? `${_chalk().default.bold.yellow(`${updatedTestsPending} skipped`)}, ` + : '') + + (updatedTestsTodo > 0 + ? `${_chalk().default.bold.magenta(`${updatedTestsTodo} todo`)}, ` + : '') + + (updatedTestsPassed > 0 + ? `${_chalk().default.bold.green(`${updatedTestsPassed} passed`)}, ` + : '') + }${updatedTestsTotal} total`; + const snapshots = `${ + _chalk().default.bold('Snapshots: ') + + (snapshotsFailed + ? `${_chalk().default.bold.red(`${snapshotsFailed} failed`)}, ` + : '') + + (snapshotsOutdated && !snapshotsDidUpdate + ? `${_chalk().default.bold.yellow(`${snapshotsOutdated} obsolete`)}, ` + : '') + + (snapshotsOutdated && snapshotsDidUpdate + ? `${_chalk().default.bold.green(`${snapshotsOutdated} removed`)}, ` + : '') + + (snapshotsFilesRemoved && !snapshotsDidUpdate + ? `${_chalk().default.bold.yellow( + `${(0, _jestUtil().pluralize)( + 'file', + snapshotsFilesRemoved + )} obsolete` + )}, ` + : '') + + (snapshotsFilesRemoved && snapshotsDidUpdate + ? `${_chalk().default.bold.green( + `${(0, _jestUtil().pluralize)('file', snapshotsFilesRemoved)} removed` + )}, ` + : '') + + (snapshotsUpdated + ? `${_chalk().default.bold.green(`${snapshotsUpdated} updated`)}, ` + : '') + + (snapshotsAdded + ? `${_chalk().default.bold.green(`${snapshotsAdded} written`)}, ` + : '') + + (snapshotsPassed + ? `${_chalk().default.bold.green(`${snapshotsPassed} passed`)}, ` + : '') + }${snapshotsTotal} total`; + const time = renderTime(runTime, estimatedTime, width); + return [...optionalLines, suites, tests, snapshots, time].join('\n'); +} diff --git a/node_modules/@jest/reporters/build/getWatermarks.js b/node_modules/@jest/reporters/build/getWatermarks.js new file mode 100644 index 0000000..e7f2e1f --- /dev/null +++ b/node_modules/@jest/reporters/build/getWatermarks.js @@ -0,0 +1,38 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getWatermarks; +function _istanbulLibReport() { + const data = _interopRequireDefault(require('istanbul-lib-report')); + _istanbulLibReport = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getWatermarks(config) { + const defaultWatermarks = _istanbulLibReport().default.getDefaultWatermarks(); + const {coverageThreshold} = config; + if (!coverageThreshold || !coverageThreshold.global) { + return defaultWatermarks; + } + const keys = ['branches', 'functions', 'lines', 'statements']; + return keys.reduce((watermarks, key) => { + const value = coverageThreshold.global[key]; + if (value !== undefined) { + watermarks[key][1] = value; + } + return watermarks; + }, defaultWatermarks); +} diff --git a/node_modules/@jest/reporters/build/index.d.ts b/node_modules/@jest/reporters/build/index.d.ts new file mode 100644 index 0000000..4ce958c --- /dev/null +++ b/node_modules/@jest/reporters/build/index.d.ts @@ -0,0 +1,284 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import {AggregatedResult} from '@jest/test-result'; +import type {AssertionResult} from '@jest/test-result'; +import {Config} from '@jest/types'; +import {SnapshotSummary} from '@jest/test-result'; +import type {Suite} from '@jest/test-result'; +import {Test} from '@jest/test-result'; +import {TestCaseResult} from '@jest/test-result'; +import {TestContext} from '@jest/test-result'; +import {TestResult} from '@jest/test-result'; + +export {AggregatedResult}; + +export declare class BaseReporter implements Reporter { + private _error?; + log(message: string): void; + onRunStart( + _results?: AggregatedResult, + _options?: ReporterOnStartOptions, + ): void; + onTestCaseResult(_test: Test, _testCaseResult: TestCaseResult): void; + onTestResult( + _test?: Test, + _testResult?: TestResult, + _results?: AggregatedResult, + ): void; + onTestStart(_test?: Test): void; + onRunComplete( + _testContexts?: Set, + _aggregatedResults?: AggregatedResult, + ): Promise | void; + protected _setError(error: Error): void; + getLastError(): Error | undefined; +} + +export {Config}; + +export declare class CoverageReporter extends BaseReporter { + private readonly _context; + private readonly _coverageMap; + private readonly _globalConfig; + private readonly _sourceMapStore; + private readonly _v8CoverageResults; + static readonly filename: string; + constructor(globalConfig: Config.GlobalConfig, context: ReporterContext); + onTestResult(_test: Test, testResult: TestResult): void; + onRunComplete( + testContexts: Set, + aggregatedResults: AggregatedResult, + ): Promise; + private _addUntestedFiles; + private _checkThreshold; + private _getCoverageResult; +} + +export declare class DefaultReporter extends BaseReporter { + private _clear; + private readonly _err; + protected _globalConfig: Config.GlobalConfig; + private readonly _out; + private readonly _status; + private readonly _bufferedOutput; + static readonly filename: string; + constructor(globalConfig: Config.GlobalConfig); + protected __wrapStdio( + stream: NodeJS.WritableStream | NodeJS.WriteStream, + ): void; + forceFlushBufferedOutput(): void; + protected __clearStatus(): void; + protected __printStatus(): void; + onRunStart( + aggregatedResults: AggregatedResult, + options: ReporterOnStartOptions, + ): void; + onTestStart(test: Test): void; + onTestCaseResult(test: Test, testCaseResult: TestCaseResult): void; + onRunComplete(): void; + onTestResult( + test: Test, + testResult: TestResult, + aggregatedResults: AggregatedResult, + ): void; + testFinished( + config: Config.ProjectConfig, + testResult: TestResult, + aggregatedResults: AggregatedResult, + ): void; + printTestFileHeader( + testPath: string, + config: Config.ProjectConfig, + result: TestResult, + ): void; + printTestFileFailureMessage( + _testPath: string, + _config: Config.ProjectConfig, + result: TestResult, + ): void; +} + +declare function formatTestPath( + config: Config.GlobalConfig | Config.ProjectConfig, + testPath: string, +): string; + +declare function getResultHeader( + result: TestResult, + globalConfig: Config.GlobalConfig, + projectConfig?: Config.ProjectConfig, +): string; + +declare function getSnapshotStatus( + snapshot: TestResult['snapshot'], + afterUpdate: boolean, +): Array; + +declare function getSnapshotSummary( + snapshots: SnapshotSummary, + globalConfig: Config.GlobalConfig, + updateCommand: string, +): Array; + +declare function getSummary( + aggregatedResults: AggregatedResult, + options?: SummaryOptions, +): string; + +export declare class GitHubActionsReporter extends BaseReporter { + #private; + static readonly filename: string; + onTestFileResult({context}: Test, {testResults}: TestResult): void; +} + +export declare class NotifyReporter extends BaseReporter { + private readonly _notifier; + private readonly _globalConfig; + private _context; + static readonly filename: string; + constructor(globalConfig: Config.GlobalConfig, context: ReporterContext); + onRunComplete(testContexts: Set, result: AggregatedResult): void; +} + +declare function printDisplayName(config: Config.ProjectConfig): string; + +declare function relativePath( + config: Config.GlobalConfig | Config.ProjectConfig, + testPath: string, +): { + basename: string; + dirname: string; +}; + +export declare interface Reporter { + readonly onTestResult?: ( + test: Test, + testResult: TestResult, + aggregatedResult: AggregatedResult, + ) => Promise | void; + readonly onTestFileResult?: ( + test: Test, + testResult: TestResult, + aggregatedResult: AggregatedResult, + ) => Promise | void; + readonly onTestCaseResult?: ( + test: Test, + testCaseResult: TestCaseResult, + ) => Promise | void; + readonly onRunStart: ( + results: AggregatedResult, + options: ReporterOnStartOptions, + ) => Promise | void; + readonly onTestStart?: (test: Test) => Promise | void; + readonly onTestFileStart?: (test: Test) => Promise | void; + readonly onRunComplete: ( + testContexts: Set, + results: AggregatedResult, + ) => Promise | void; + readonly getLastError: () => Error | void; +} + +export declare type ReporterContext = { + firstRun: boolean; + previousSuccess: boolean; + changedFiles?: Set; + sourcesRelatedToTestsInChangedFiles?: Set; + startRun?: (globalConfig: Config.GlobalConfig) => unknown; +}; + +export declare type ReporterOnStartOptions = { + estimatedTime: number; + showStatus: boolean; +}; + +export {SnapshotSummary}; + +export declare type SummaryOptions = { + currentTestCases?: Array<{ + test: Test; + testCaseResult: TestCaseResult; + }>; + estimatedTime?: number; + roundTime?: boolean; + width?: number; + showSeed?: boolean; + seed?: number; +}; + +export declare class SummaryReporter extends BaseReporter { + private _estimatedTime; + private readonly _globalConfig; + static readonly filename: string; + constructor(globalConfig: Config.GlobalConfig); + private _write; + onRunStart( + aggregatedResults: AggregatedResult, + options: ReporterOnStartOptions, + ): void; + onRunComplete( + testContexts: Set, + aggregatedResults: AggregatedResult, + ): void; + private _printSnapshotSummary; + private _printSummary; + private _getTestSummary; +} + +export {Test}; + +export {TestCaseResult}; + +export {TestContext}; + +export {TestResult}; + +declare function trimAndFormatPath( + pad: number, + config: Config.ProjectConfig | Config.GlobalConfig, + testPath: string, + columns: number, +): string; + +export declare const utils: { + formatTestPath: typeof formatTestPath; + getResultHeader: typeof getResultHeader; + getSnapshotStatus: typeof getSnapshotStatus; + getSnapshotSummary: typeof getSnapshotSummary; + getSummary: typeof getSummary; + printDisplayName: typeof printDisplayName; + relativePath: typeof relativePath; + trimAndFormatPath: typeof trimAndFormatPath; +}; + +export declare class VerboseReporter extends DefaultReporter { + protected _globalConfig: Config.GlobalConfig; + static readonly filename: string; + constructor(globalConfig: Config.GlobalConfig); + protected __wrapStdio( + stream: NodeJS.WritableStream | NodeJS.WriteStream, + ): void; + static filterTestResults( + testResults: Array, + ): Array; + static groupTestsBySuites(testResults: Array): Suite; + onTestResult( + test: Test, + result: TestResult, + aggregatedResults: AggregatedResult, + ): void; + private _logTestResults; + private _logSuite; + private _getIcon; + private _logTest; + private _logTests; + private _logTodoOrPendingTest; + private _logLine; +} + +export {}; diff --git a/node_modules/@jest/reporters/build/index.js b/node_modules/@jest/reporters/build/index.js new file mode 100644 index 0000000..060b1fa --- /dev/null +++ b/node_modules/@jest/reporters/build/index.js @@ -0,0 +1,88 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'BaseReporter', { + enumerable: true, + get: function () { + return _BaseReporter.default; + } +}); +Object.defineProperty(exports, 'CoverageReporter', { + enumerable: true, + get: function () { + return _CoverageReporter.default; + } +}); +Object.defineProperty(exports, 'DefaultReporter', { + enumerable: true, + get: function () { + return _DefaultReporter.default; + } +}); +Object.defineProperty(exports, 'GitHubActionsReporter', { + enumerable: true, + get: function () { + return _GitHubActionsReporter.default; + } +}); +Object.defineProperty(exports, 'NotifyReporter', { + enumerable: true, + get: function () { + return _NotifyReporter.default; + } +}); +Object.defineProperty(exports, 'SummaryReporter', { + enumerable: true, + get: function () { + return _SummaryReporter.default; + } +}); +Object.defineProperty(exports, 'VerboseReporter', { + enumerable: true, + get: function () { + return _VerboseReporter.default; + } +}); +exports.utils = void 0; +var _formatTestPath = _interopRequireDefault(require('./formatTestPath')); +var _getResultHeader = _interopRequireDefault(require('./getResultHeader')); +var _getSnapshotStatus = _interopRequireDefault(require('./getSnapshotStatus')); +var _getSnapshotSummary = _interopRequireDefault( + require('./getSnapshotSummary') +); +var _getSummary = _interopRequireDefault(require('./getSummary')); +var _printDisplayName = _interopRequireDefault(require('./printDisplayName')); +var _relativePath = _interopRequireDefault(require('./relativePath')); +var _trimAndFormatPath = _interopRequireDefault(require('./trimAndFormatPath')); +var _BaseReporter = _interopRequireDefault(require('./BaseReporter')); +var _CoverageReporter = _interopRequireDefault(require('./CoverageReporter')); +var _DefaultReporter = _interopRequireDefault(require('./DefaultReporter')); +var _GitHubActionsReporter = _interopRequireDefault( + require('./GitHubActionsReporter') +); +var _NotifyReporter = _interopRequireDefault(require('./NotifyReporter')); +var _SummaryReporter = _interopRequireDefault(require('./SummaryReporter')); +var _VerboseReporter = _interopRequireDefault(require('./VerboseReporter')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const utils = { + formatTestPath: _formatTestPath.default, + getResultHeader: _getResultHeader.default, + getSnapshotStatus: _getSnapshotStatus.default, + getSnapshotSummary: _getSnapshotSummary.default, + getSummary: _getSummary.default, + printDisplayName: _printDisplayName.default, + relativePath: _relativePath.default, + trimAndFormatPath: _trimAndFormatPath.default +}; +exports.utils = utils; diff --git a/node_modules/@jest/reporters/build/printDisplayName.js b/node_modules/@jest/reporters/build/printDisplayName.js new file mode 100644 index 0000000..95b21d8 --- /dev/null +++ b/node_modules/@jest/reporters/build/printDisplayName.js @@ -0,0 +1,35 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = printDisplayName; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function printDisplayName(config) { + const {displayName} = config; + const white = _chalk().default.reset.inverse.white; + if (!displayName) { + return ''; + } + const {name, color} = displayName; + const chosenColor = _chalk().default.reset.inverse[color] + ? _chalk().default.reset.inverse[color] + : white; + return _chalk().default.supportsColor ? chosenColor(` ${name} `) : name; +} diff --git a/node_modules/@jest/reporters/build/relativePath.js b/node_modules/@jest/reporters/build/relativePath.js new file mode 100644 index 0000000..ff01293 --- /dev/null +++ b/node_modules/@jest/reporters/build/relativePath.js @@ -0,0 +1,72 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = relativePath; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function relativePath(config, testPath) { + // this function can be called with ProjectConfigs or GlobalConfigs. GlobalConfigs + // do not have config.cwd, only config.rootDir. Try using config.cwd, fallback + // to config.rootDir. (Also, some unit just use config.rootDir, which is ok) + testPath = path().relative(config.cwd || config.rootDir, testPath); + const dirname = path().dirname(testPath); + const basename = path().basename(testPath); + return { + basename, + dirname + }; +} diff --git a/node_modules/@jest/reporters/build/trimAndFormatPath.js b/node_modules/@jest/reporters/build/trimAndFormatPath.js new file mode 100644 index 0000000..e7ac3b6 --- /dev/null +++ b/node_modules/@jest/reporters/build/trimAndFormatPath.js @@ -0,0 +1,118 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = trimAndFormatPath; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _slash() { + const data = _interopRequireDefault(require('slash')); + _slash = function () { + return data; + }; + return data; +} +var _relativePath = _interopRequireDefault(require('./relativePath')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function trimAndFormatPath(pad, config, testPath, columns) { + const maxLength = columns - pad; + const relative = (0, _relativePath.default)(config, testPath); + const {basename} = relative; + let {dirname} = relative; + + // length is ok + if ((dirname + path().sep + basename).length <= maxLength) { + return (0, _slash().default)( + _chalk().default.dim(dirname + path().sep) + + _chalk().default.bold(basename) + ); + } + + // we can fit trimmed dirname and full basename + const basenameLength = basename.length; + if (basenameLength + 4 < maxLength) { + const dirnameLength = maxLength - 4 - basenameLength; + dirname = `...${dirname.slice( + dirname.length - dirnameLength, + dirname.length + )}`; + return (0, _slash().default)( + _chalk().default.dim(dirname + path().sep) + + _chalk().default.bold(basename) + ); + } + if (basenameLength + 4 === maxLength) { + return (0, _slash().default)( + _chalk().default.dim(`...${path().sep}`) + _chalk().default.bold(basename) + ); + } + + // can't fit dirname, but can fit trimmed basename + return (0, _slash().default)( + _chalk().default.bold( + `...${basename.slice(basename.length - maxLength - 4, basename.length)}` + ) + ); +} diff --git a/node_modules/@jest/reporters/build/types.js b/node_modules/@jest/reporters/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/reporters/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/reporters/build/wrapAnsiString.js b/node_modules/@jest/reporters/build/wrapAnsiString.js new file mode 100644 index 0000000..11b2546 --- /dev/null +++ b/node_modules/@jest/reporters/build/wrapAnsiString.js @@ -0,0 +1,69 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = wrapAnsiString; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// word-wrap a string that contains ANSI escape sequences. +// ANSI escape sequences do not add to the string length. +function wrapAnsiString(string, terminalWidth) { + if (terminalWidth === 0) { + // if the terminal width is zero, don't bother word-wrapping + return string; + } + const ANSI_REGEXP = /[\u001b\u009b]\[\d{1,2}m/gu; + const tokens = []; + let lastIndex = 0; + let match; + while ((match = ANSI_REGEXP.exec(string))) { + const ansi = match[0]; + const index = match.index; + if (index != lastIndex) { + tokens.push(['string', string.slice(lastIndex, index)]); + } + tokens.push(['ansi', ansi]); + lastIndex = index + ansi.length; + } + if (lastIndex != string.length - 1) { + tokens.push(['string', string.slice(lastIndex, string.length)]); + } + let lastLineLength = 0; + return tokens + .reduce( + (lines, [kind, token]) => { + if (kind === 'string') { + if (lastLineLength + token.length > terminalWidth) { + while (token.length) { + const chunk = token.slice(0, terminalWidth - lastLineLength); + const remaining = token.slice( + terminalWidth - lastLineLength, + token.length + ); + lines[lines.length - 1] += chunk; + lastLineLength += chunk.length; + token = remaining; + if (token.length) { + lines.push(''); + lastLineLength = 0; + } + } + } else { + lines[lines.length - 1] += token; + lastLineLength += token.length; + } + } else { + lines[lines.length - 1] += token; + } + return lines; + }, + [''] + ) + .join('\n'); +} diff --git a/node_modules/@jest/reporters/package.json b/node_modules/@jest/reporters/package.json new file mode 100644 index 0000000..0ed8f4d --- /dev/null +++ b/node_modules/@jest/reporters/package.json @@ -0,0 +1,81 @@ +{ + "name": "@jest/reporters", + "description": "Jest's reporters", + "version": "29.2.2", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@bcoe/v8-coverage": "^0.2.3", + "@jest/console": "^29.2.1", + "@jest/test-result": "^29.2.1", + "@jest/transform": "^29.2.2", + "@jest/types": "^29.2.1", + "@jridgewell/trace-mapping": "^0.3.15", + "@types/node": "*", + "chalk": "^4.0.0", + "collect-v8-coverage": "^1.0.0", + "exit": "^0.1.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "istanbul-lib-coverage": "^3.0.0", + "istanbul-lib-instrument": "^5.1.0", + "istanbul-lib-report": "^3.0.0", + "istanbul-lib-source-maps": "^4.0.0", + "istanbul-reports": "^3.1.3", + "jest-message-util": "^29.2.1", + "jest-util": "^29.2.1", + "jest-worker": "^29.2.1", + "slash": "^3.0.0", + "string-length": "^4.0.1", + "strip-ansi": "^6.0.0", + "v8-to-istanbul": "^9.0.1" + }, + "devDependencies": { + "@jest/test-utils": "^29.2.1", + "@tsd/typescript": "~4.8.2", + "@types/exit": "^0.1.30", + "@types/glob": "^7.1.1", + "@types/graceful-fs": "^4.1.3", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-lib-instrument": "^1.7.2", + "@types/istanbul-lib-report": "^3.0.0", + "@types/istanbul-lib-source-maps": "^4.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node-notifier": "^8.0.0", + "jest-resolve": "^29.2.2", + "mock-fs": "^5.1.2", + "tsd-lite": "^0.6.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-reporters" + }, + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "homepage": "https://jestjs.io/", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/@jest/schemas/LICENSE b/node_modules/@jest/schemas/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/schemas/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/schemas/README.md b/node_modules/@jest/schemas/README.md new file mode 100644 index 0000000..b2a1d12 --- /dev/null +++ b/node_modules/@jest/schemas/README.md @@ -0,0 +1,3 @@ +# `@jest/schemas` + +Experimental and currently incomplete module for JSON schemas for [Jest's](https://jestjs.io/) configuration. diff --git a/node_modules/@jest/schemas/build/index.d.ts b/node_modules/@jest/schemas/build/index.d.ts new file mode 100644 index 0000000..cb4cad3 --- /dev/null +++ b/node_modules/@jest/schemas/build/index.d.ts @@ -0,0 +1,72 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import {Static} from '@sinclair/typebox'; +import {TBoolean} from '@sinclair/typebox'; +import {TNull} from '@sinclair/typebox'; +import {TNumber} from '@sinclair/typebox'; +import {TObject} from '@sinclair/typebox'; +import {TPartial} from '@sinclair/typebox'; +import {TReadonly} from '@sinclair/typebox'; +import {TString} from '@sinclair/typebox'; + +declare const RawSnapshotFormat: TPartial< + TObject<{ + callToJSON: TReadonly; + compareKeys: TReadonly; + escapeRegex: TReadonly; + escapeString: TReadonly; + highlight: TReadonly; + indent: TReadonly; + maxDepth: TReadonly; + maxWidth: TReadonly; + min: TReadonly; + printBasicPrototype: TReadonly; + printFunctionName: TReadonly; + theme: TReadonly< + TPartial< + TObject<{ + comment: TReadonly; + content: TReadonly; + prop: TReadonly; + tag: TReadonly; + value: TReadonly; + }> + > + >; + }> +>; + +export declare const SnapshotFormat: TPartial< + TObject<{ + callToJSON: TReadonly; + compareKeys: TReadonly; + escapeRegex: TReadonly; + escapeString: TReadonly; + highlight: TReadonly; + indent: TReadonly; + maxDepth: TReadonly; + maxWidth: TReadonly; + min: TReadonly; + printBasicPrototype: TReadonly; + printFunctionName: TReadonly; + theme: TReadonly< + TPartial< + TObject<{ + comment: TReadonly; + content: TReadonly; + prop: TReadonly; + tag: TReadonly; + value: TReadonly; + }> + > + >; + }> +>; + +export declare type SnapshotFormat = Static; + +export {}; diff --git a/node_modules/@jest/schemas/build/index.js b/node_modules/@jest/schemas/build/index.js new file mode 100644 index 0000000..32187f8 --- /dev/null +++ b/node_modules/@jest/schemas/build/index.js @@ -0,0 +1,65 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.SnapshotFormat = void 0; + +function _typebox() { + const data = require('@sinclair/typebox'); + + _typebox = function () { + return data; + }; + + return data; +} + +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +const RawSnapshotFormat = _typebox().Type.Partial( + _typebox().Type.Object({ + callToJSON: _typebox().Type.Readonly(_typebox().Type.Boolean()), + compareKeys: _typebox().Type.Readonly(_typebox().Type.Null()), + escapeRegex: _typebox().Type.Readonly(_typebox().Type.Boolean()), + escapeString: _typebox().Type.Readonly(_typebox().Type.Boolean()), + highlight: _typebox().Type.Readonly(_typebox().Type.Boolean()), + indent: _typebox().Type.Readonly( + _typebox().Type.Number({ + minimum: 0 + }) + ), + maxDepth: _typebox().Type.Readonly( + _typebox().Type.Number({ + minimum: 0 + }) + ), + maxWidth: _typebox().Type.Readonly( + _typebox().Type.Number({ + minimum: 0 + }) + ), + min: _typebox().Type.Readonly(_typebox().Type.Boolean()), + printBasicPrototype: _typebox().Type.Readonly(_typebox().Type.Boolean()), + printFunctionName: _typebox().Type.Readonly(_typebox().Type.Boolean()), + theme: _typebox().Type.Readonly( + _typebox().Type.Partial( + _typebox().Type.Object({ + comment: _typebox().Type.Readonly(_typebox().Type.String()), + content: _typebox().Type.Readonly(_typebox().Type.String()), + prop: _typebox().Type.Readonly(_typebox().Type.String()), + tag: _typebox().Type.Readonly(_typebox().Type.String()), + value: _typebox().Type.Readonly(_typebox().Type.String()) + }) + ) + ) + }) +); + +const SnapshotFormat = _typebox().Type.Strict(RawSnapshotFormat); + +exports.SnapshotFormat = SnapshotFormat; diff --git a/node_modules/@jest/schemas/package.json b/node_modules/@jest/schemas/package.json new file mode 100644 index 0000000..db1399c --- /dev/null +++ b/node_modules/@jest/schemas/package.json @@ -0,0 +1,29 @@ +{ + "name": "@jest/schemas", + "version": "29.0.0", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-schemas" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@sinclair/typebox": "^0.24.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "75006e46c76f6fda14bbc0548f86edb2ba087cd2" +} diff --git a/node_modules/@jest/source-map/LICENSE b/node_modules/@jest/source-map/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/source-map/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/source-map/build/getCallsite.js b/node_modules/@jest/source-map/build/getCallsite.js new file mode 100644 index 0000000..aad5b78 --- /dev/null +++ b/node_modules/@jest/source-map/build/getCallsite.js @@ -0,0 +1,85 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getCallsite; +function _traceMapping() { + const data = require('@jridgewell/trace-mapping'); + _traceMapping = function () { + return data; + }; + return data; +} +function _callsites() { + const data = _interopRequireDefault(require('callsites')); + _callsites = function () { + return data; + }; + return data; +} +function _gracefulFs() { + const data = require('graceful-fs'); + _gracefulFs = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Copied from https://github.com/rexxars/sourcemap-decorate-callsites/blob/5b9735a156964973a75dc62fd2c7f0c1975458e8/lib/index.js#L113-L158 +const addSourceMapConsumer = (callsite, tracer) => { + const getLineNumber = callsite.getLineNumber.bind(callsite); + const getColumnNumber = callsite.getColumnNumber.bind(callsite); + let position = null; + function getPosition() { + if (!position) { + position = (0, _traceMapping().originalPositionFor)(tracer, { + column: getColumnNumber() ?? -1, + line: getLineNumber() ?? -1 + }); + } + return position; + } + Object.defineProperties(callsite, { + getColumnNumber: { + value() { + const value = getPosition().column; + return value == null || value === 0 ? getColumnNumber() : value; + }, + writable: false + }, + getLineNumber: { + value() { + const value = getPosition().line; + return value == null || value === 0 ? getLineNumber() : value; + }, + writable: false + } + }); +}; +function getCallsite(level, sourceMaps) { + const levelAfterThisCall = level + 1; + const stack = (0, _callsites().default)()[levelAfterThisCall]; + const sourceMapFileName = sourceMaps?.get(stack.getFileName() ?? ''); + if (sourceMapFileName != null && sourceMapFileName !== '') { + try { + const sourceMap = (0, _gracefulFs().readFileSync)( + sourceMapFileName, + 'utf8' + ); + addSourceMapConsumer(stack, new (_traceMapping().TraceMap)(sourceMap)); + } catch { + // ignore + } + } + return stack; +} diff --git a/node_modules/@jest/source-map/build/index.d.ts b/node_modules/@jest/source-map/build/index.d.ts new file mode 100644 index 0000000..cd44216 --- /dev/null +++ b/node_modules/@jest/source-map/build/index.d.ts @@ -0,0 +1,16 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import callsites = require('callsites'); + +export declare function getCallsite( + level: number, + sourceMaps?: SourceMapRegistry | null, +): callsites.CallSite; + +export declare type SourceMapRegistry = Map; + +export {}; diff --git a/node_modules/@jest/source-map/build/index.js b/node_modules/@jest/source-map/build/index.js new file mode 100644 index 0000000..c4f4cf9 --- /dev/null +++ b/node_modules/@jest/source-map/build/index.js @@ -0,0 +1,15 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'getCallsite', { + enumerable: true, + get: function () { + return _getCallsite.default; + } +}); +var _getCallsite = _interopRequireDefault(require('./getCallsite')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} diff --git a/node_modules/@jest/source-map/build/types.js b/node_modules/@jest/source-map/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/source-map/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/source-map/package.json b/node_modules/@jest/source-map/package.json new file mode 100644 index 0000000..6c19985 --- /dev/null +++ b/node_modules/@jest/source-map/package.json @@ -0,0 +1,34 @@ +{ + "name": "@jest/source-map", + "version": "29.2.0", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-source-map" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.15", + "callsites": "^3.0.0", + "graceful-fs": "^4.2.9" + }, + "devDependencies": { + "@types/graceful-fs": "^4.1.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "ee5b37a4f4433afcfffb0356cea47739d8092287" +} diff --git a/node_modules/@jest/test-result/LICENSE b/node_modules/@jest/test-result/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/test-result/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/test-result/build/formatTestResults.js b/node_modules/@jest/test-result/build/formatTestResults.js new file mode 100644 index 0000000..28c228d --- /dev/null +++ b/node_modules/@jest/test-result/build/formatTestResults.js @@ -0,0 +1,51 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = formatTestResults; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const formatTestResult = (testResult, codeCoverageFormatter, reporter) => { + if (testResult.testExecError) { + const now = Date.now(); + return { + assertionResults: testResult.testResults, + coverage: {}, + endTime: now, + message: testResult.failureMessage ?? testResult.testExecError.message, + name: testResult.testFilePath, + startTime: now, + status: 'failed', + summary: '' + }; + } + const allTestsPassed = testResult.numFailingTests === 0; + return { + assertionResults: testResult.testResults, + coverage: + codeCoverageFormatter != null + ? codeCoverageFormatter(testResult.coverage, reporter) + : testResult.coverage, + endTime: testResult.perfStats.end, + message: testResult.failureMessage ?? '', + name: testResult.testFilePath, + startTime: testResult.perfStats.start, + status: allTestsPassed ? 'passed' : 'failed', + summary: '' + }; +}; +function formatTestResults(results, codeCoverageFormatter, reporter) { + const testResults = results.testResults.map(testResult => + formatTestResult(testResult, codeCoverageFormatter, reporter) + ); + return { + ...results, + testResults + }; +} diff --git a/node_modules/@jest/test-result/build/helpers.js b/node_modules/@jest/test-result/build/helpers.js new file mode 100644 index 0000000..0f6e0e9 --- /dev/null +++ b/node_modules/@jest/test-result/build/helpers.js @@ -0,0 +1,175 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.makeEmptyAggregatedTestResult = + exports.createEmptyTestResult = + exports.buildFailureTestResult = + exports.addResult = + void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const makeEmptyAggregatedTestResult = () => ({ + numFailedTestSuites: 0, + numFailedTests: 0, + numPassedTestSuites: 0, + numPassedTests: 0, + numPendingTestSuites: 0, + numPendingTests: 0, + numRuntimeErrorTestSuites: 0, + numTodoTests: 0, + numTotalTestSuites: 0, + numTotalTests: 0, + openHandles: [], + snapshot: { + added: 0, + didUpdate: false, + // is set only after the full run + failure: false, + filesAdded: 0, + // combines individual test results + removed files after the full run + filesRemoved: 0, + filesRemovedList: [], + filesUnmatched: 0, + filesUpdated: 0, + matched: 0, + total: 0, + unchecked: 0, + uncheckedKeysByFile: [], + unmatched: 0, + updated: 0 + }, + startTime: 0, + success: true, + testResults: [], + wasInterrupted: false +}); +exports.makeEmptyAggregatedTestResult = makeEmptyAggregatedTestResult; +const buildFailureTestResult = (testPath, err) => ({ + console: undefined, + displayName: undefined, + failureMessage: null, + leaks: false, + numFailingTests: 0, + numPassingTests: 0, + numPendingTests: 0, + numTodoTests: 0, + openHandles: [], + perfStats: { + end: 0, + runtime: 0, + slow: false, + start: 0 + }, + skipped: false, + snapshot: { + added: 0, + fileDeleted: false, + matched: 0, + unchecked: 0, + uncheckedKeys: [], + unmatched: 0, + updated: 0 + }, + testExecError: err, + testFilePath: testPath, + testResults: [] +}); + +// Add individual test result to an aggregated test result +exports.buildFailureTestResult = buildFailureTestResult; +const addResult = (aggregatedResults, testResult) => { + // `todos` are new as of Jest 24, and not all runners return it. + // Set it to `0` to avoid `NaN` + if (!testResult.numTodoTests) { + testResult.numTodoTests = 0; + } + aggregatedResults.testResults.push(testResult); + aggregatedResults.numTotalTests += + testResult.numPassingTests + + testResult.numFailingTests + + testResult.numPendingTests + + testResult.numTodoTests; + aggregatedResults.numFailedTests += testResult.numFailingTests; + aggregatedResults.numPassedTests += testResult.numPassingTests; + aggregatedResults.numPendingTests += testResult.numPendingTests; + aggregatedResults.numTodoTests += testResult.numTodoTests; + if (testResult.testExecError) { + aggregatedResults.numRuntimeErrorTestSuites++; + } + if (testResult.skipped) { + aggregatedResults.numPendingTestSuites++; + } else if (testResult.numFailingTests > 0 || testResult.testExecError) { + aggregatedResults.numFailedTestSuites++; + } else { + aggregatedResults.numPassedTestSuites++; + } + + // Snapshot data + if (testResult.snapshot.added) { + aggregatedResults.snapshot.filesAdded++; + } + if (testResult.snapshot.fileDeleted) { + aggregatedResults.snapshot.filesRemoved++; + } + if (testResult.snapshot.unmatched) { + aggregatedResults.snapshot.filesUnmatched++; + } + if (testResult.snapshot.updated) { + aggregatedResults.snapshot.filesUpdated++; + } + aggregatedResults.snapshot.added += testResult.snapshot.added; + aggregatedResults.snapshot.matched += testResult.snapshot.matched; + aggregatedResults.snapshot.unchecked += testResult.snapshot.unchecked; + if ( + testResult.snapshot.uncheckedKeys != null && + testResult.snapshot.uncheckedKeys.length > 0 + ) { + aggregatedResults.snapshot.uncheckedKeysByFile.push({ + filePath: testResult.testFilePath, + keys: testResult.snapshot.uncheckedKeys + }); + } + aggregatedResults.snapshot.unmatched += testResult.snapshot.unmatched; + aggregatedResults.snapshot.updated += testResult.snapshot.updated; + aggregatedResults.snapshot.total += + testResult.snapshot.added + + testResult.snapshot.matched + + testResult.snapshot.unmatched + + testResult.snapshot.updated; +}; +exports.addResult = addResult; +const createEmptyTestResult = () => ({ + leaks: false, + // That's legacy code, just adding it as needed for typing + numFailingTests: 0, + numPassingTests: 0, + numPendingTests: 0, + numTodoTests: 0, + openHandles: [], + perfStats: { + end: 0, + runtime: 0, + slow: false, + start: 0 + }, + skipped: false, + snapshot: { + added: 0, + fileDeleted: false, + matched: 0, + unchecked: 0, + uncheckedKeys: [], + unmatched: 0, + updated: 0 + }, + testFilePath: '', + testResults: [] +}); +exports.createEmptyTestResult = createEmptyTestResult; diff --git a/node_modules/@jest/test-result/build/index.d.ts b/node_modules/@jest/test-result/build/index.d.ts new file mode 100644 index 0000000..53a370e --- /dev/null +++ b/node_modules/@jest/test-result/build/index.d.ts @@ -0,0 +1,230 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config} from '@jest/types'; +import type {ConsoleBuffer} from '@jest/console'; +import type {CoverageMap} from 'istanbul-lib-coverage'; +import type {CoverageMapData} from 'istanbul-lib-coverage'; +import type {IHasteFS} from 'jest-haste-map'; +import type {IModuleMap} from 'jest-haste-map'; +import type Resolver from 'jest-resolve'; +import type {TestResult as TestResult_2} from '@jest/types'; +import type {TransformTypes} from '@jest/types'; +import type {V8Coverage} from 'collect-v8-coverage'; + +export declare const addResult: ( + aggregatedResults: AggregatedResult, + testResult: TestResult, +) => void; + +export declare type AggregatedResult = AggregatedResultWithoutCoverage & { + coverageMap?: CoverageMap | null; +}; + +declare type AggregatedResultWithoutCoverage = { + numFailedTests: number; + numFailedTestSuites: number; + numPassedTests: number; + numPassedTestSuites: number; + numPendingTests: number; + numTodoTests: number; + numPendingTestSuites: number; + numRuntimeErrorTestSuites: number; + numTotalTests: number; + numTotalTestSuites: number; + openHandles: Array; + snapshot: SnapshotSummary; + startTime: number; + success: boolean; + testResults: Array; + wasInterrupted: boolean; + runExecError?: SerializableError; +}; + +export declare type AssertionLocation = { + fullName: string; + path: string; +}; + +export declare type AssertionResult = TestResult_2.AssertionResult; + +export declare const buildFailureTestResult: ( + testPath: string, + err: SerializableError, +) => TestResult; + +declare type CodeCoverageFormatter = ( + coverage: CoverageMapData | null | undefined, + reporter: CodeCoverageReporter, +) => Record | null | undefined; + +declare type CodeCoverageReporter = unknown; + +export declare const createEmptyTestResult: () => TestResult; + +export declare type FailedAssertion = { + matcherName?: string; + message?: string; + actual?: unknown; + pass?: boolean; + passed?: boolean; + expected?: unknown; + isNot?: boolean; + stack?: string; + error?: unknown; +}; + +declare type FormattedAssertionResult = Pick< + AssertionResult, + 'ancestorTitles' | 'fullName' | 'location' | 'status' | 'title' | 'duration' +> & { + failureMessages: AssertionResult['failureMessages'] | null; +}; + +declare type FormattedTestResult = { + message: string; + name: string; + summary: string; + status: 'failed' | 'passed'; + startTime: number; + endTime: number; + coverage: unknown; + assertionResults: Array; +}; + +export declare type FormattedTestResults = { + coverageMap?: CoverageMap | null | undefined; + numFailedTests: number; + numFailedTestSuites: number; + numPassedTests: number; + numPassedTestSuites: number; + numPendingTests: number; + numPendingTestSuites: number; + numRuntimeErrorTestSuites: number; + numTotalTests: number; + numTotalTestSuites: number; + snapshot: SnapshotSummary; + startTime: number; + success: boolean; + testResults: Array; + wasInterrupted: boolean; +}; + +export declare function formatTestResults( + results: AggregatedResult, + codeCoverageFormatter?: CodeCoverageFormatter, + reporter?: CodeCoverageReporter, +): FormattedTestResults; + +export declare const makeEmptyAggregatedTestResult: () => AggregatedResult; + +export declare interface RuntimeTransformResult + extends TransformTypes.TransformResult { + wrapperLength: number; +} + +export declare type SerializableError = TestResult_2.SerializableError; + +export declare type SnapshotSummary = { + added: number; + didUpdate: boolean; + failure: boolean; + filesAdded: number; + filesRemoved: number; + filesRemovedList: Array; + filesUnmatched: number; + filesUpdated: number; + matched: number; + total: number; + unchecked: number; + uncheckedKeysByFile: Array; + unmatched: number; + updated: number; +}; + +export declare type Status = AssertionResult['status']; + +export declare type Suite = { + title: string; + suites: Array; + tests: Array; +}; + +export declare type Test = { + context: TestContext; + duration?: number; + path: string; +}; + +export declare type TestCaseResult = AssertionResult; + +export declare type TestContext = { + config: Config.ProjectConfig; + hasteFS: IHasteFS; + moduleMap: IModuleMap; + resolver: Resolver; +}; + +export declare type TestEvents = { + 'test-file-start': [Test]; + 'test-file-success': [Test, TestResult]; + 'test-file-failure': [Test, SerializableError]; + 'test-case-result': [string, AssertionResult]; +}; + +export declare type TestFileEvent< + T extends keyof TestEvents = keyof TestEvents, +> = (eventName: T, args: TestEvents[T]) => unknown; + +export declare type TestResult = { + console?: ConsoleBuffer; + coverage?: CoverageMapData; + displayName?: Config.DisplayName; + failureMessage?: string | null; + leaks: boolean; + memoryUsage?: number; + numFailingTests: number; + numPassingTests: number; + numPendingTests: number; + numTodoTests: number; + openHandles: Array; + perfStats: { + end: number; + runtime: number; + slow: boolean; + start: number; + }; + skipped: boolean; + snapshot: { + added: number; + fileDeleted: boolean; + matched: number; + unchecked: number; + uncheckedKeys: Array; + unmatched: number; + updated: number; + }; + testExecError?: SerializableError; + testFilePath: string; + testResults: Array; + v8Coverage?: V8CoverageResult; +}; + +export declare type TestResultsProcessor = ( + results: AggregatedResult, +) => AggregatedResult; + +declare type UncheckedSnapshot = { + filePath: string; + keys: Array; +}; + +export declare type V8CoverageResult = Array<{ + codeTransformResult: RuntimeTransformResult | undefined; + result: V8Coverage[number]; +}>; + +export {}; diff --git a/node_modules/@jest/test-result/build/index.js b/node_modules/@jest/test-result/build/index.js new file mode 100644 index 0000000..2f7f67a --- /dev/null +++ b/node_modules/@jest/test-result/build/index.js @@ -0,0 +1,40 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'addResult', { + enumerable: true, + get: function () { + return _helpers.addResult; + } +}); +Object.defineProperty(exports, 'buildFailureTestResult', { + enumerable: true, + get: function () { + return _helpers.buildFailureTestResult; + } +}); +Object.defineProperty(exports, 'createEmptyTestResult', { + enumerable: true, + get: function () { + return _helpers.createEmptyTestResult; + } +}); +Object.defineProperty(exports, 'formatTestResults', { + enumerable: true, + get: function () { + return _formatTestResults.default; + } +}); +Object.defineProperty(exports, 'makeEmptyAggregatedTestResult', { + enumerable: true, + get: function () { + return _helpers.makeEmptyAggregatedTestResult; + } +}); +var _formatTestResults = _interopRequireDefault(require('./formatTestResults')); +var _helpers = require('./helpers'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} diff --git a/node_modules/@jest/test-result/build/types.js b/node_modules/@jest/test-result/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/test-result/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/test-result/package.json b/node_modules/@jest/test-result/package.json new file mode 100644 index 0000000..9b076a4 --- /dev/null +++ b/node_modules/@jest/test-result/package.json @@ -0,0 +1,32 @@ +{ + "name": "@jest/test-result", + "version": "29.2.1", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-test-result" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/console": "^29.2.1", + "@jest/types": "^29.2.1", + "@types/istanbul-lib-coverage": "^2.0.0", + "collect-v8-coverage": "^1.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "4551c0fdd4d25b7206824957c7bcc6baf61e63bf" +} diff --git a/node_modules/@jest/test-sequencer/LICENSE b/node_modules/@jest/test-sequencer/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/test-sequencer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/test-sequencer/build/index.d.ts b/node_modules/@jest/test-sequencer/build/index.d.ts new file mode 100644 index 0000000..a8f92f5 --- /dev/null +++ b/node_modules/@jest/test-sequencer/build/index.d.ts @@ -0,0 +1,85 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {AggregatedResult} from '@jest/test-result'; +import type {Test} from '@jest/test-result'; +import type {TestContext} from '@jest/test-result'; + +declare type Cache_2 = { + [key: string]: [0 | 1, number] | undefined; +}; + +export declare type ShardOptions = { + shardIndex: number; + shardCount: number; +}; + +/** + * The TestSequencer will ultimately decide which tests should run first. + * It is responsible for storing and reading from a local cache + * map that stores context information for a given test, such as how long it + * took to run during the last run and if it has failed or not. + * Such information is used on: + * TestSequencer.sort(tests: Array) + * to sort the order of the provided tests. + * + * After the results are collected, + * TestSequencer.cacheResults(tests: Array, results: AggregatedResult) + * is called to store/update this information on the cache map. + */ +declare class TestSequencer { + private readonly _cache; + _getCachePath(testContext: TestContext): string; + _getCache(test: Test): Cache_2; + private _shardPosition; + /** + * Select tests for shard requested via --shard=shardIndex/shardCount + * Sharding is applied before sorting + * + * @param tests All tests + * @param options shardIndex and shardIndex to select + * + * @example + * ```typescript + * class CustomSequencer extends Sequencer { + * shard(tests, { shardIndex, shardCount }) { + * const shardSize = Math.ceil(tests.length / options.shardCount); + * const shardStart = shardSize * (options.shardIndex - 1); + * const shardEnd = shardSize * options.shardIndex; + * return [...tests] + * .sort((a, b) => (a.path > b.path ? 1 : -1)) + * .slice(shardStart, shardEnd); + * } + * } + * ``` + */ + shard( + tests: Array, + options: ShardOptions, + ): Array | Promise>; + /** + * Sort test to determine order of execution + * Sorting is applied after sharding + * @param tests + * + * ```typescript + * class CustomSequencer extends Sequencer { + * sort(tests) { + * const copyTests = Array.from(tests); + * return [...tests].sort((a, b) => (a.path > b.path ? 1 : -1)); + * } + * } + * ``` + */ + sort(tests: Array): Array | Promise>; + allFailedTests(tests: Array): Array | Promise>; + cacheResults(tests: Array, results: AggregatedResult): void; + private hasFailed; + private time; +} +export default TestSequencer; + +export {}; diff --git a/node_modules/@jest/test-sequencer/build/index.js b/node_modules/@jest/test-sequencer/build/index.js new file mode 100644 index 0000000..e5f4b7b --- /dev/null +++ b/node_modules/@jest/test-sequencer/build/index.js @@ -0,0 +1,288 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function crypto() { + const data = _interopRequireWildcard(require('crypto')); + crypto = function () { + return data; + }; + return data; +} +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _slash() { + const data = _interopRequireDefault(require('slash')); + _slash = function () { + return data; + }; + return data; +} +function _jestHasteMap() { + const data = _interopRequireDefault(require('jest-haste-map')); + _jestHasteMap = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const FAIL = 0; +const SUCCESS = 1; +/** + * The TestSequencer will ultimately decide which tests should run first. + * It is responsible for storing and reading from a local cache + * map that stores context information for a given test, such as how long it + * took to run during the last run and if it has failed or not. + * Such information is used on: + * TestSequencer.sort(tests: Array) + * to sort the order of the provided tests. + * + * After the results are collected, + * TestSequencer.cacheResults(tests: Array, results: AggregatedResult) + * is called to store/update this information on the cache map. + */ +class TestSequencer { + _cache = new Map(); + _getCachePath(testContext) { + const {config} = testContext; + const HasteMapClass = _jestHasteMap().default.getStatic(config); + return HasteMapClass.getCacheFilePath( + config.cacheDirectory, + `perf-cache-${config.id}` + ); + } + _getCache(test) { + const {context} = test; + if (!this._cache.has(context) && context.config.cache) { + const cachePath = this._getCachePath(context); + if (fs().existsSync(cachePath)) { + try { + this._cache.set( + context, + JSON.parse(fs().readFileSync(cachePath, 'utf8')) + ); + } catch {} + } + } + let cache = this._cache.get(context); + if (!cache) { + cache = {}; + this._cache.set(context, cache); + } + return cache; + } + _shardPosition(options) { + const shardRest = options.suiteLength % options.shardCount; + const ratio = options.suiteLength / options.shardCount; + return new Array(options.shardIndex) + .fill(true) + .reduce((acc, _, shardIndex) => { + const dangles = shardIndex < shardRest; + const shardSize = dangles ? Math.ceil(ratio) : Math.floor(ratio); + return acc + shardSize; + }, 0); + } + + /** + * Select tests for shard requested via --shard=shardIndex/shardCount + * Sharding is applied before sorting + * + * @param tests All tests + * @param options shardIndex and shardIndex to select + * + * @example + * ```typescript + * class CustomSequencer extends Sequencer { + * shard(tests, { shardIndex, shardCount }) { + * const shardSize = Math.ceil(tests.length / options.shardCount); + * const shardStart = shardSize * (options.shardIndex - 1); + * const shardEnd = shardSize * options.shardIndex; + * return [...tests] + * .sort((a, b) => (a.path > b.path ? 1 : -1)) + * .slice(shardStart, shardEnd); + * } + * } + * ``` + */ + shard(tests, options) { + const shardStart = this._shardPosition({ + shardCount: options.shardCount, + shardIndex: options.shardIndex - 1, + suiteLength: tests.length + }); + const shardEnd = this._shardPosition({ + shardCount: options.shardCount, + shardIndex: options.shardIndex, + suiteLength: tests.length + }); + return tests + .map(test => { + const relativeTestPath = path().posix.relative( + (0, _slash().default)(test.context.config.rootDir), + (0, _slash().default)(test.path) + ); + return { + hash: crypto() + .createHash('sha1') + .update(relativeTestPath) + .digest('hex'), + test + }; + }) + .sort((a, b) => (a.hash < b.hash ? -1 : a.hash > b.hash ? 1 : 0)) + .slice(shardStart, shardEnd) + .map(result => result.test); + } + + /** + * Sort test to determine order of execution + * Sorting is applied after sharding + * @param tests + * + * ```typescript + * class CustomSequencer extends Sequencer { + * sort(tests) { + * const copyTests = Array.from(tests); + * return [...tests].sort((a, b) => (a.path > b.path ? 1 : -1)); + * } + * } + * ``` + */ + sort(tests) { + /** + * Sorting tests is very important because it has a great impact on the + * user-perceived responsiveness and speed of the test run. + * + * If such information is on cache, tests are sorted based on: + * -> Has it failed during the last run ? + * Since it's important to provide the most expected feedback as quickly + * as possible. + * -> How long it took to run ? + * Because running long tests first is an effort to minimize worker idle + * time at the end of a long test run. + * And if that information is not available they are sorted based on file size + * since big test files usually take longer to complete. + * + * Note that a possible improvement would be to analyse other information + * from the file other than its size. + * + */ + const stats = {}; + const fileSize = ({path, context: {hasteFS}}) => + stats[path] || (stats[path] = hasteFS.getSize(path) ?? 0); + tests.forEach(test => { + test.duration = this.time(test); + }); + return tests.sort((testA, testB) => { + const failedA = this.hasFailed(testA); + const failedB = this.hasFailed(testB); + const hasTimeA = testA.duration != null; + if (failedA !== failedB) { + return failedA === true ? -1 : 1; + } else if (hasTimeA != (testB.duration != null)) { + // If only one of two tests has timing information, run it last + return hasTimeA ? 1 : -1; + } else if (testA.duration != null && testB.duration != null) { + return testA.duration < testB.duration ? 1 : -1; + } else { + return fileSize(testA) < fileSize(testB) ? 1 : -1; + } + }); + } + allFailedTests(tests) { + const hasFailed = (cache, test) => cache[test.path]?.[0] === FAIL; + return this.sort( + tests.filter(test => hasFailed(this._getCache(test), test)) + ); + } + cacheResults(tests, results) { + const map = Object.create(null); + tests.forEach(test => (map[test.path] = test)); + results.testResults.forEach(testResult => { + const test = map[testResult.testFilePath]; + if (test != null && !testResult.skipped) { + const cache = this._getCache(test); + const perf = testResult.perfStats; + cache[testResult.testFilePath] = [ + testResult.numFailingTests ? FAIL : SUCCESS, + perf.runtime || 0 + ]; + } + }); + this._cache.forEach((cache, context) => + fs().writeFileSync(this._getCachePath(context), JSON.stringify(cache)) + ); + } + hasFailed(test) { + const cache = this._getCache(test); + return cache[test.path]?.[0] === FAIL; + } + time(test) { + const cache = this._getCache(test); + return cache[test.path]?.[1]; + } +} +exports.default = TestSequencer; diff --git a/node_modules/@jest/test-sequencer/package.json b/node_modules/@jest/test-sequencer/package.json new file mode 100644 index 0000000..2501880 --- /dev/null +++ b/node_modules/@jest/test-sequencer/package.json @@ -0,0 +1,36 @@ +{ + "name": "@jest/test-sequencer", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-test-sequencer" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/test-result": "^29.2.1", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.2.1", + "slash": "^3.0.0" + }, + "devDependencies": { + "@jest/test-utils": "^29.2.1", + "@types/graceful-fs": "^4.1.3" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/@jest/transform/LICENSE b/node_modules/@jest/transform/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/transform/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/transform/build/ScriptTransformer.js b/node_modules/@jest/transform/build/ScriptTransformer.js new file mode 100644 index 0000000..7252284 --- /dev/null +++ b/node_modules/@jest/transform/build/ScriptTransformer.js @@ -0,0 +1,979 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.createScriptTransformer = createScriptTransformer; +exports.createTranspilingRequire = createTranspilingRequire; +function _crypto() { + const data = require('crypto'); + _crypto = function () { + return data; + }; + return data; +} +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _core() { + const data = require('@babel/core'); + _core = function () { + return data; + }; + return data; +} +function _babelPluginIstanbul() { + const data = _interopRequireDefault(require('babel-plugin-istanbul')); + _babelPluginIstanbul = function () { + return data; + }; + return data; +} +function _convertSourceMap() { + const data = require('convert-source-map'); + _convertSourceMap = function () { + return data; + }; + return data; +} +function _fastJsonStableStringify() { + const data = _interopRequireDefault(require('fast-json-stable-stringify')); + _fastJsonStableStringify = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _pirates() { + const data = require('pirates'); + _pirates = function () { + return data; + }; + return data; +} +function _slash() { + const data = _interopRequireDefault(require('slash')); + _slash = function () { + return data; + }; + return data; +} +function _writeFileAtomic() { + const data = require('write-file-atomic'); + _writeFileAtomic = function () { + return data; + }; + return data; +} +function _jestHasteMap() { + const data = _interopRequireDefault(require('jest-haste-map')); + _jestHasteMap = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _enhanceUnexpectedTokenMessage = _interopRequireDefault( + require('./enhanceUnexpectedTokenMessage') +); +var _runtimeErrorsAndWarnings = require('./runtimeErrorsAndWarnings'); +var _shouldInstrument = _interopRequireDefault(require('./shouldInstrument')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// @ts-expect-error: should just be `require.resolve`, but the tests mess that up + +// Use `require` to avoid TS rootDir +const {version: VERSION} = require('../package.json'); +// This data structure is used to avoid recalculating some data every time that +// we need to transform a file. Since ScriptTransformer is instantiated for each +// file we need to keep this object in the local scope of this module. +const projectCaches = new Map(); + +// To reset the cache for specific changesets (rather than package version). +const CACHE_VERSION = '1'; +async function waitForPromiseWithCleanup(promise, cleanup) { + try { + await promise; + } finally { + cleanup(); + } +} + +// type predicate +function isTransformerFactory(t) { + return typeof t.createTransformer === 'function'; +} +class ScriptTransformer { + _cache; + _transformCache = new Map(); + _transformsAreLoaded = false; + constructor(_config, _cacheFS) { + this._config = _config; + this._cacheFS = _cacheFS; + const configString = (0, _fastJsonStableStringify().default)(this._config); + let projectCache = projectCaches.get(configString); + if (!projectCache) { + projectCache = { + configString, + ignorePatternsRegExp: calcIgnorePatternRegExp(this._config), + transformRegExp: calcTransformRegExp(this._config), + transformedFiles: new Map() + }; + projectCaches.set(configString, projectCache); + } + this._cache = projectCache; + } + _buildCacheKeyFromFileInfo( + fileData, + filename, + transformOptions, + transformerCacheKey + ) { + if (transformerCacheKey != null) { + return (0, _crypto().createHash)('sha1') + .update(transformerCacheKey) + .update(CACHE_VERSION) + .digest('hex') + .substring(0, 32); + } + return (0, _crypto().createHash)('sha1') + .update(fileData) + .update(transformOptions.configString) + .update(transformOptions.instrument ? 'instrument' : '') + .update(filename) + .update(CACHE_VERSION) + .digest('hex') + .substring(0, 32); + } + _getCacheKey(fileData, filename, options) { + const configString = this._cache.configString; + const {transformer, transformerConfig = {}} = + this._getTransformer(filename) ?? {}; + let transformerCacheKey = undefined; + const transformOptions = { + ...options, + cacheFS: this._cacheFS, + config: this._config, + configString, + transformerConfig + }; + if (typeof transformer?.getCacheKey === 'function') { + transformerCacheKey = transformer.getCacheKey( + fileData, + filename, + transformOptions + ); + } + return this._buildCacheKeyFromFileInfo( + fileData, + filename, + transformOptions, + transformerCacheKey + ); + } + async _getCacheKeyAsync(fileData, filename, options) { + const configString = this._cache.configString; + const {transformer, transformerConfig = {}} = + this._getTransformer(filename) ?? {}; + let transformerCacheKey = undefined; + const transformOptions = { + ...options, + cacheFS: this._cacheFS, + config: this._config, + configString, + transformerConfig + }; + if (transformer) { + const getCacheKey = + transformer.getCacheKeyAsync ?? transformer.getCacheKey; + if (typeof getCacheKey === 'function') { + transformerCacheKey = await getCacheKey( + fileData, + filename, + transformOptions + ); + } + } + return this._buildCacheKeyFromFileInfo( + fileData, + filename, + transformOptions, + transformerCacheKey + ); + } + _createFolderFromCacheKey(filename, cacheKey) { + const HasteMapClass = _jestHasteMap().default.getStatic(this._config); + const baseCacheDir = HasteMapClass.getCacheFilePath( + this._config.cacheDirectory, + `jest-transform-cache-${this._config.id}`, + VERSION + ); + // Create sub folders based on the cacheKey to avoid creating one + // directory with many files. + const cacheDir = path().join(baseCacheDir, cacheKey[0] + cacheKey[1]); + const cacheFilenamePrefix = path() + .basename(filename, path().extname(filename)) + .replace(/\W/g, ''); + const cachePath = (0, _slash().default)( + path().join(cacheDir, `${cacheFilenamePrefix}_${cacheKey}`) + ); + (0, _jestUtil().createDirectory)(cacheDir); + return cachePath; + } + _getFileCachePath(filename, content, options) { + const cacheKey = this._getCacheKey(content, filename, options); + return this._createFolderFromCacheKey(filename, cacheKey); + } + async _getFileCachePathAsync(filename, content, options) { + const cacheKey = await this._getCacheKeyAsync(content, filename, options); + return this._createFolderFromCacheKey(filename, cacheKey); + } + _getTransformPath(filename) { + const transformRegExp = this._cache.transformRegExp; + if (!transformRegExp) { + return undefined; + } + for (let i = 0; i < transformRegExp.length; i++) { + if (transformRegExp[i][0].test(filename)) { + return transformRegExp[i][1]; + } + } + return undefined; + } + async loadTransformers() { + await Promise.all( + this._config.transform.map( + async ([, transformPath, transformerConfig]) => { + let transformer = await (0, _jestUtil().requireOrImportModule)( + transformPath + ); + if (transformer == null) { + throw new Error( + (0, _runtimeErrorsAndWarnings.makeInvalidTransformerError)( + transformPath + ) + ); + } + if (isTransformerFactory(transformer)) { + transformer = transformer.createTransformer(transformerConfig); + } + if ( + typeof transformer.process !== 'function' && + typeof transformer.processAsync !== 'function' + ) { + throw new Error( + (0, _runtimeErrorsAndWarnings.makeInvalidTransformerError)( + transformPath + ) + ); + } + const res = { + transformer, + transformerConfig + }; + this._transformCache.set(transformPath, res); + } + ) + ); + this._transformsAreLoaded = true; + } + _getTransformer(filename) { + if (!this._transformsAreLoaded) { + throw new Error( + 'Jest: Transformers have not been loaded yet - make sure to run `loadTransformers` and wait for it to complete before starting to transform files' + ); + } + if (this._config.transform.length === 0) { + return null; + } + const transformPath = this._getTransformPath(filename); + if (transformPath == null) { + return null; + } + const cached = this._transformCache.get(transformPath); + if (cached != null) { + return cached; + } + throw new Error( + `Jest was unable to load the transformer defined for ${filename}. This is a bug in Jest, please open up an issue` + ); + } + _instrumentFile(filename, input, canMapToInput, options) { + const inputCode = typeof input === 'string' ? input : input.code; + const inputMap = typeof input === 'string' ? null : input.map; + const result = (0, _core().transformSync)(inputCode, { + auxiliaryCommentBefore: ' istanbul ignore next ', + babelrc: false, + caller: { + name: '@jest/transform', + supportsDynamicImport: options.supportsDynamicImport, + supportsExportNamespaceFrom: options.supportsExportNamespaceFrom, + supportsStaticESM: options.supportsStaticESM, + supportsTopLevelAwait: options.supportsTopLevelAwait + }, + configFile: false, + filename, + plugins: [ + [ + _babelPluginIstanbul().default, + { + compact: false, + // files outside `cwd` will not be instrumented + cwd: this._config.rootDir, + exclude: [], + extension: false, + inputSourceMap: inputMap, + useInlineSourceMaps: false + } + ] + ], + sourceMaps: canMapToInput ? 'both' : false + }); + if (result?.code != null) { + return result; + } + return input; + } + _buildTransformResult( + filename, + cacheFilePath, + content, + transformer, + shouldCallTransform, + options, + processed, + sourceMapPath + ) { + let transformed = { + code: content, + map: null + }; + if (transformer && shouldCallTransform) { + if (processed != null && typeof processed.code === 'string') { + transformed = processed; + } else { + const transformPath = this._getTransformPath(filename); + invariant(transformPath); + throw new Error( + (0, _runtimeErrorsAndWarnings.makeInvalidReturnValueError)( + transformPath + ) + ); + } + } + if (transformed.map == null || transformed.map === '') { + try { + //Could be a potential freeze here. + //See: https://github.com/facebook/jest/pull/5177#discussion_r158883570 + const inlineSourceMap = (0, _convertSourceMap().fromSource)( + transformed.code + ); + if (inlineSourceMap) { + transformed.map = inlineSourceMap.toObject(); + } + } catch { + const transformPath = this._getTransformPath(filename); + invariant(transformPath); + console.warn( + (0, _runtimeErrorsAndWarnings.makeInvalidSourceMapWarning)( + filename, + transformPath + ) + ); + } + } + + // That means that the transform has a custom instrumentation + // logic and will handle it based on `config.collectCoverage` option + const transformWillInstrument = + shouldCallTransform && transformer && transformer.canInstrument; + + // Apply instrumentation to the code if necessary, keeping the instrumented code and new map + let map = transformed.map; + let code; + if (transformWillInstrument !== true && options.instrument) { + /** + * We can map the original source code to the instrumented code ONLY if + * - the process of transforming the code produced a source map e.g. ts-jest + * - we did not transform the source code + * + * Otherwise we cannot make any statements about how the instrumented code corresponds to the original code, + * and we should NOT emit any source maps + * + */ + const shouldEmitSourceMaps = + (transformer != null && map != null) || transformer == null; + const instrumented = this._instrumentFile( + filename, + transformed, + shouldEmitSourceMaps, + options + ); + code = + typeof instrumented === 'string' ? instrumented : instrumented.code; + map = typeof instrumented === 'string' ? null : instrumented.map; + } else { + code = transformed.code; + } + if (map != null) { + const sourceMapContent = + typeof map === 'string' ? map : JSON.stringify(map); + invariant(sourceMapPath, 'We should always have default sourceMapPath'); + writeCacheFile(sourceMapPath, sourceMapContent); + } else { + sourceMapPath = null; + } + writeCodeCacheFile(cacheFilePath, code); + return { + code, + originalCode: content, + sourceMapPath + }; + } + transformSource(filepath, content, options) { + const filename = (0, _jestUtil().tryRealpath)(filepath); + const {transformer, transformerConfig = {}} = + this._getTransformer(filename) ?? {}; + const cacheFilePath = this._getFileCachePath(filename, content, options); + const sourceMapPath = `${cacheFilePath}.map`; + // Ignore cache if `config.cache` is set (--no-cache) + const code = this._config.cache ? readCodeCacheFile(cacheFilePath) : null; + if (code != null) { + // This is broken: we return the code, and a path for the source map + // directly from the cache. But, nothing ensures the source map actually + // matches that source code. They could have gotten out-of-sync in case + // two separate processes write concurrently to the same cache files. + return { + code, + originalCode: content, + sourceMapPath + }; + } + let processed = null; + let shouldCallTransform = false; + if (transformer && this.shouldTransform(filename)) { + shouldCallTransform = true; + assertSyncTransformer(transformer, this._getTransformPath(filename)); + processed = transformer.process(content, filename, { + ...options, + cacheFS: this._cacheFS, + config: this._config, + configString: this._cache.configString, + transformerConfig + }); + } + return this._buildTransformResult( + filename, + cacheFilePath, + content, + transformer, + shouldCallTransform, + options, + processed, + sourceMapPath + ); + } + async transformSourceAsync(filepath, content, options) { + const filename = (0, _jestUtil().tryRealpath)(filepath); + const {transformer, transformerConfig = {}} = + this._getTransformer(filename) ?? {}; + const cacheFilePath = await this._getFileCachePathAsync( + filename, + content, + options + ); + const sourceMapPath = `${cacheFilePath}.map`; + // Ignore cache if `config.cache` is set (--no-cache) + const code = this._config.cache ? readCodeCacheFile(cacheFilePath) : null; + if (code != null) { + // This is broken: we return the code, and a path for the source map + // directly from the cache. But, nothing ensures the source map actually + // matches that source code. They could have gotten out-of-sync in case + // two separate processes write concurrently to the same cache files. + return { + code, + originalCode: content, + sourceMapPath + }; + } + let processed = null; + let shouldCallTransform = false; + if (transformer && this.shouldTransform(filename)) { + shouldCallTransform = true; + const process = transformer.processAsync ?? transformer.process; + + // This is probably dead code since `_getTransformerAsync` already asserts this + invariant( + typeof process === 'function', + 'A transformer must always export either a `process` or `processAsync`' + ); + processed = await process(content, filename, { + ...options, + cacheFS: this._cacheFS, + config: this._config, + configString: this._cache.configString, + transformerConfig + }); + } + return this._buildTransformResult( + filename, + cacheFilePath, + content, + transformer, + shouldCallTransform, + options, + processed, + sourceMapPath + ); + } + async _transformAndBuildScriptAsync( + filename, + options, + transformOptions, + fileSource + ) { + const {isInternalModule} = options; + let fileContent = fileSource ?? this._cacheFS.get(filename); + if (fileContent == null) { + fileContent = fs().readFileSync(filename, 'utf8'); + this._cacheFS.set(filename, fileContent); + } + const content = stripShebang(fileContent); + let code = content; + let sourceMapPath = null; + const willTransform = + isInternalModule !== true && + (transformOptions.instrument || this.shouldTransform(filename)); + try { + if (willTransform) { + const transformedSource = await this.transformSourceAsync( + filename, + content, + transformOptions + ); + code = transformedSource.code; + sourceMapPath = transformedSource.sourceMapPath; + } + return { + code, + originalCode: content, + sourceMapPath + }; + } catch (e) { + if (!(e instanceof Error)) { + throw e; + } + throw (0, _enhanceUnexpectedTokenMessage.default)(e); + } + } + _transformAndBuildScript(filename, options, transformOptions, fileSource) { + const {isInternalModule} = options; + let fileContent = fileSource ?? this._cacheFS.get(filename); + if (fileContent == null) { + fileContent = fs().readFileSync(filename, 'utf8'); + this._cacheFS.set(filename, fileContent); + } + const content = stripShebang(fileContent); + let code = content; + let sourceMapPath = null; + const willTransform = + isInternalModule !== true && + (transformOptions.instrument || this.shouldTransform(filename)); + try { + if (willTransform) { + const transformedSource = this.transformSource( + filename, + content, + transformOptions + ); + code = transformedSource.code; + sourceMapPath = transformedSource.sourceMapPath; + } + return { + code, + originalCode: content, + sourceMapPath + }; + } catch (e) { + if (!(e instanceof Error)) { + throw e; + } + throw (0, _enhanceUnexpectedTokenMessage.default)(e); + } + } + async transformAsync(filename, options, fileSource) { + const instrument = + options.coverageProvider === 'babel' && + (0, _shouldInstrument.default)(filename, options, this._config); + const scriptCacheKey = getScriptCacheKey(filename, instrument); + let result = this._cache.transformedFiles.get(scriptCacheKey); + if (result) { + return result; + } + result = await this._transformAndBuildScriptAsync( + filename, + options, + { + ...options, + instrument + }, + fileSource + ); + if (scriptCacheKey) { + this._cache.transformedFiles.set(scriptCacheKey, result); + } + return result; + } + transform(filename, options, fileSource) { + const instrument = + options.coverageProvider === 'babel' && + (0, _shouldInstrument.default)(filename, options, this._config); + const scriptCacheKey = getScriptCacheKey(filename, instrument); + let result = this._cache.transformedFiles.get(scriptCacheKey); + if (result) { + return result; + } + result = this._transformAndBuildScript( + filename, + options, + { + ...options, + instrument + }, + fileSource + ); + if (scriptCacheKey) { + this._cache.transformedFiles.set(scriptCacheKey, result); + } + return result; + } + transformJson(filename, options, fileSource) { + const {isInternalModule} = options; + const willTransform = + isInternalModule !== true && this.shouldTransform(filename); + if (willTransform) { + const {code: transformedJsonSource} = this.transformSource( + filename, + fileSource, + { + ...options, + instrument: false + } + ); + return transformedJsonSource; + } + return fileSource; + } + async requireAndTranspileModule( + moduleName, + callback, + options = { + applyInteropRequireDefault: true, + instrument: false, + supportsDynamicImport: false, + supportsExportNamespaceFrom: false, + supportsStaticESM: false, + supportsTopLevelAwait: false + } + ) { + let transforming = false; + const {applyInteropRequireDefault, ...transformOptions} = options; + const revertHook = (0, _pirates().addHook)( + (code, filename) => { + try { + transforming = true; + return ( + this.transformSource(filename, code, transformOptions).code || code + ); + } finally { + transforming = false; + } + }, + { + // Exclude `mjs` extension when addHook because pirates don't support hijack es module + exts: this._config.moduleFileExtensions + .filter(ext => ext !== 'mjs') + .map(ext => `.${ext}`), + ignoreNodeModules: false, + matcher: filename => { + if (transforming) { + // Don't transform any dependency required by the transformer itself + return false; + } + return this.shouldTransform(filename); + } + } + ); + try { + const module = await (0, _jestUtil().requireOrImportModule)( + moduleName, + applyInteropRequireDefault + ); + if (!callback) { + revertHook(); + return module; + } + const cbResult = callback(module); + if ((0, _jestUtil().isPromise)(cbResult)) { + return await waitForPromiseWithCleanup(cbResult, revertHook).then( + () => module + ); + } + return module; + } finally { + revertHook(); + } + } + shouldTransform(filename) { + const ignoreRegexp = this._cache.ignorePatternsRegExp; + const isIgnored = ignoreRegexp ? ignoreRegexp.test(filename) : false; + return this._config.transform.length !== 0 && !isIgnored; + } +} + +// TODO: do we need to define the generics twice? +async function createTranspilingRequire(config) { + const transformer = await createScriptTransformer(config); + return async function requireAndTranspileModule( + resolverPath, + applyInteropRequireDefault = false + ) { + const transpiledModule = await transformer.requireAndTranspileModule( + resolverPath, + // eslint-disable-next-line @typescript-eslint/no-empty-function + () => {}, + { + applyInteropRequireDefault, + instrument: false, + supportsDynamicImport: false, + // this might be true, depending on node version. + supportsExportNamespaceFrom: false, + supportsStaticESM: false, + supportsTopLevelAwait: false + } + ); + return transpiledModule; + }; +} +const removeFile = path => { + try { + fs().unlinkSync(path); + } catch {} +}; +const stripShebang = content => { + // If the file data starts with a shebang remove it. Leaves the empty line + // to keep stack trace line numbers correct. + if (content.startsWith('#!')) { + return content.replace(/^#!.*/, ''); + } else { + return content; + } +}; + +/** + * This is like `writeCacheFile` but with an additional sanity checksum. We + * cannot use the same technique for source maps because we expose source map + * cache file paths directly to callsites, with the expectation they can read + * it right away. This is not a great system, because source map cache file + * could get corrupted, out-of-sync, etc. + */ +function writeCodeCacheFile(cachePath, code) { + const checksum = (0, _crypto().createHash)('sha1') + .update(code) + .digest('hex') + .substring(0, 32); + writeCacheFile(cachePath, `${checksum}\n${code}`); +} + +/** + * Read counterpart of `writeCodeCacheFile`. We verify that the content of the + * file matches the checksum, in case some kind of corruption happened. This + * could happen if an older version of `jest-runtime` writes non-atomically to + * the same cache, for example. + */ +function readCodeCacheFile(cachePath) { + const content = readCacheFile(cachePath); + if (content == null) { + return null; + } + const code = content.substring(33); + const checksum = (0, _crypto().createHash)('sha1') + .update(code) + .digest('hex') + .substring(0, 32); + if (checksum === content.substring(0, 32)) { + return code; + } + return null; +} + +/** + * Writing to the cache atomically relies on 'rename' being atomic on most + * file systems. Doing atomic write reduces the risk of corruption by avoiding + * two processes to write to the same file at the same time. It also reduces + * the risk of reading a file that's being overwritten at the same time. + */ +const writeCacheFile = (cachePath, fileData) => { + try { + (0, _writeFileAtomic().sync)(cachePath, fileData, { + encoding: 'utf8', + fsync: false + }); + } catch (e) { + if (!(e instanceof Error)) { + throw e; + } + if (cacheWriteErrorSafeToIgnore(e, cachePath)) { + return; + } + e.message = `jest: failed to cache transform results in: ${cachePath}\nFailure message: ${e.message}`; + removeFile(cachePath); + throw e; + } +}; + +/** + * On Windows, renames are not atomic, leading to EPERM exceptions when two + * processes attempt to rename to the same target file at the same time. + * If the target file exists we can be reasonably sure another process has + * legitimately won a cache write race and ignore the error. + */ +const cacheWriteErrorSafeToIgnore = (e, cachePath) => + process.platform === 'win32' && + e.code === 'EPERM' && + fs().existsSync(cachePath); +const readCacheFile = cachePath => { + if (!fs().existsSync(cachePath)) { + return null; + } + let fileData; + try { + fileData = fs().readFileSync(cachePath, 'utf8'); + } catch (e) { + if (!(e instanceof Error)) { + throw e; + } + // on windows write-file-atomic is not atomic which can + // result in this error + if (e.code === 'ENOENT' && process.platform === 'win32') { + return null; + } + e.message = `jest: failed to read cache file: ${cachePath}\nFailure message: ${e.message}`; + removeFile(cachePath); + throw e; + } + if (fileData == null) { + // We must have somehow created the file but failed to write to it, + // let's delete it and retry. + removeFile(cachePath); + } + return fileData; +}; +const getScriptCacheKey = (filename, instrument) => { + const mtime = fs().statSync(filename).mtime; + return `${filename}_${mtime.getTime()}${instrument ? '_instrumented' : ''}`; +}; +const calcIgnorePatternRegExp = config => { + if ( + config.transformIgnorePatterns == null || + config.transformIgnorePatterns.length === 0 + ) { + return undefined; + } + return new RegExp(config.transformIgnorePatterns.join('|')); +}; +const calcTransformRegExp = config => { + if (!config.transform.length) { + return undefined; + } + const transformRegexp = []; + for (let i = 0; i < config.transform.length; i++) { + transformRegexp.push([ + new RegExp(config.transform[i][0]), + config.transform[i][1], + config.transform[i][2] + ]); + } + return transformRegexp; +}; +function invariant(condition, message) { + if (condition == null || condition === false || condition === '') { + throw new Error(message); + } +} +function assertSyncTransformer(transformer, name) { + invariant(name); + invariant( + typeof transformer.process === 'function', + (0, _runtimeErrorsAndWarnings.makeInvalidSyncTransformerError)(name) + ); +} +async function createScriptTransformer(config, cacheFS = new Map()) { + const transformer = new ScriptTransformer(config, cacheFS); + await transformer.loadTransformers(); + return transformer; +} diff --git a/node_modules/@jest/transform/build/enhanceUnexpectedTokenMessage.js b/node_modules/@jest/transform/build/enhanceUnexpectedTokenMessage.js new file mode 100644 index 0000000..e39aeb4 --- /dev/null +++ b/node_modules/@jest/transform/build/enhanceUnexpectedTokenMessage.js @@ -0,0 +1,76 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = handlePotentialSyntaxError; +exports.enhanceUnexpectedTokenMessage = enhanceUnexpectedTokenMessage; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const DOT = ' \u2022 '; +function handlePotentialSyntaxError(e) { + if (e.codeFrame != null) { + e.stack = `${e.message}\n${e.codeFrame}`; + } + if ( + // `instanceof` might come from the wrong context + e.name === 'SyntaxError' && + !e.message.includes(' expected') + ) { + throw enhanceUnexpectedTokenMessage(e); + } + return e; +} +function enhanceUnexpectedTokenMessage(e) { + e.stack = `${_chalk().default.bold.red( + 'Jest encountered an unexpected token' + )} + +Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax. + +Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration. + +By default "node_modules" folder is ignored by transformers. + +Here's what you can do: +${DOT}If you are trying to use ECMAScript Modules, see ${_chalk().default.underline( + 'https://jestjs.io/docs/ecmascript-modules' + )} for how to enable it. +${DOT}If you are trying to use TypeScript, see ${_chalk().default.underline( + 'https://jestjs.io/docs/getting-started#using-typescript' + )} +${DOT}To have some of your "node_modules" files transformed, you can specify a custom ${_chalk().default.bold( + '"transformIgnorePatterns"' + )} in your config. +${DOT}If you need a custom transformation specify a ${_chalk().default.bold( + '"transform"' + )} option in your config. +${DOT}If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the ${_chalk().default.bold( + '"moduleNameMapper"' + )} config option. + +You'll find more details and examples of these config options in the docs: +${_chalk().default.cyan('https://jestjs.io/docs/configuration')} +For information about custom transformations, see: +${_chalk().default.cyan('https://jestjs.io/docs/code-transformation')} + +${_chalk().default.bold.red('Details:')} + +${e.stack ?? ''}`.trimRight(); + return e; +} diff --git a/node_modules/@jest/transform/build/index.d.ts b/node_modules/@jest/transform/build/index.d.ts new file mode 100644 index 0000000..e4e445c --- /dev/null +++ b/node_modules/@jest/transform/build/index.d.ts @@ -0,0 +1,237 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config} from '@jest/types'; +import type {EncodedSourceMap} from '@jridgewell/trace-mapping'; +import type {TransformTypes} from '@jest/types'; + +export declare interface AsyncTransformer { + /** + * Indicates if the transformer is capable of instrumenting the code for code coverage. + * + * If V8 coverage is _not_ active, and this is `true`, Jest will assume the code is instrumented. + * If V8 coverage is _not_ active, and this is `false`. Jest will instrument the code returned by this transformer using Babel. + */ + canInstrument?: boolean; + getCacheKey?: ( + sourceText: string, + sourcePath: string, + options: TransformOptions, + ) => string; + getCacheKeyAsync?: ( + sourceText: string, + sourcePath: string, + options: TransformOptions, + ) => Promise; + process?: ( + sourceText: string, + sourcePath: string, + options: TransformOptions, + ) => TransformedSource; + processAsync: ( + sourceText: string, + sourcePath: string, + options: TransformOptions, + ) => Promise; +} + +export declare interface CallerTransformOptions { + supportsDynamicImport: boolean; + supportsExportNamespaceFrom: boolean; + supportsStaticESM: boolean; + supportsTopLevelAwait: boolean; +} + +export declare function createScriptTransformer( + config: Config.ProjectConfig, + cacheFS?: StringMap, +): Promise; + +export declare function createTranspilingRequire( + config: Config.ProjectConfig, +): Promise< + ( + resolverPath: string, + applyInteropRequireDefault?: boolean, + ) => Promise +>; + +declare interface ErrorWithCodeFrame extends Error { + codeFrame?: string; +} + +declare interface FixedRawSourceMap extends Omit { + version: number; +} + +export declare function handlePotentialSyntaxError( + e: ErrorWithCodeFrame, +): ErrorWithCodeFrame; + +declare interface ReducedTransformOptions extends CallerTransformOptions { + instrument: boolean; +} + +declare interface RequireAndTranspileModuleOptions + extends ReducedTransformOptions { + applyInteropRequireDefault: boolean; +} + +export declare type ScriptTransformer = ScriptTransformer_2; + +declare class ScriptTransformer_2 { + private readonly _config; + private readonly _cacheFS; + private readonly _cache; + private readonly _transformCache; + private _transformsAreLoaded; + constructor(_config: Config.ProjectConfig, _cacheFS: StringMap); + private _buildCacheKeyFromFileInfo; + private _getCacheKey; + private _getCacheKeyAsync; + private _createFolderFromCacheKey; + private _getFileCachePath; + private _getFileCachePathAsync; + private _getTransformPath; + loadTransformers(): Promise; + private _getTransformer; + private _instrumentFile; + private _buildTransformResult; + transformSource( + filepath: string, + content: string, + options: ReducedTransformOptions, + ): TransformResult; + transformSourceAsync( + filepath: string, + content: string, + options: ReducedTransformOptions, + ): Promise; + private _transformAndBuildScriptAsync; + private _transformAndBuildScript; + transformAsync( + filename: string, + options: TransformationOptions, + fileSource?: string, + ): Promise; + transform( + filename: string, + options: TransformationOptions, + fileSource?: string, + ): TransformResult; + transformJson( + filename: string, + options: TransformationOptions, + fileSource: string, + ): string; + requireAndTranspileModule( + moduleName: string, + callback?: (module: ModuleType) => void | Promise, + options?: RequireAndTranspileModuleOptions, + ): Promise; + shouldTransform(filename: string): boolean; +} + +export declare function shouldInstrument( + filename: string, + options: ShouldInstrumentOptions, + config: Config.ProjectConfig, +): boolean; + +export declare interface ShouldInstrumentOptions + extends Pick< + Config.GlobalConfig, + 'collectCoverage' | 'collectCoverageFrom' | 'coverageProvider' + > { + changedFiles?: Set; + sourcesRelatedToTestsInChangedFiles?: Set; +} + +declare type StringMap = Map; + +export declare interface SyncTransformer { + /** + * Indicates if the transformer is capable of instrumenting the code for code coverage. + * + * If V8 coverage is _not_ active, and this is `true`, Jest will assume the code is instrumented. + * If V8 coverage is _not_ active, and this is `false`. Jest will instrument the code returned by this transformer using Babel. + */ + canInstrument?: boolean; + getCacheKey?: ( + sourceText: string, + sourcePath: string, + options: TransformOptions, + ) => string; + getCacheKeyAsync?: ( + sourceText: string, + sourcePath: string, + options: TransformOptions, + ) => Promise; + process: ( + sourceText: string, + sourcePath: string, + options: TransformOptions, + ) => TransformedSource; + processAsync?: ( + sourceText: string, + sourcePath: string, + options: TransformOptions, + ) => Promise; +} + +export declare interface TransformationOptions + extends ShouldInstrumentOptions, + CallerTransformOptions { + isInternalModule?: boolean; +} + +export declare type TransformedSource = { + code: string; + map?: FixedRawSourceMap | string | null; +}; + +/** + * We have both sync (`process`) and async (`processAsync`) code transformation, which both can be provided. + * `require` will always use `process`, and `import` will use `processAsync` if it exists, otherwise fall back to `process`. + * Meaning, if you use `import` exclusively you do not need `process`, but in most cases supplying both makes sense: + * Jest transpiles on demand rather than ahead of time, so the sync one needs to exist. + * + * For more info on the sync vs async model, see https://jestjs.io/docs/code-transformation#writing-custom-transformers + */ +declare type Transformer_2 = + | SyncTransformer + | AsyncTransformer; +export {Transformer_2 as Transformer}; + +export declare type TransformerCreator< + X extends Transformer_2, + TransformerConfig = unknown, +> = (transformerConfig?: TransformerConfig) => X; + +/** + * Instead of having your custom transformer implement the Transformer interface + * directly, you can choose to export a factory function to dynamically create + * transformers. This is to allow having a transformer config in your jest config. + */ +export declare type TransformerFactory = { + createTransformer: TransformerCreator; +}; + +export declare interface TransformOptions + extends ReducedTransformOptions { + /** Cached file system which is used by `jest-runtime` to improve performance. */ + cacheFS: StringMap; + /** Jest configuration of currently running project. */ + config: Config.ProjectConfig; + /** Stringified version of the `config` - useful in cache busting. */ + configString: string; + /** Transformer configuration passed through `transform` option by the user. */ + transformerConfig: TransformerConfig; +} + +export declare type TransformResult = TransformTypes.TransformResult; + +export {}; diff --git a/node_modules/@jest/transform/build/index.js b/node_modules/@jest/transform/build/index.js new file mode 100644 index 0000000..7b2d030 --- /dev/null +++ b/node_modules/@jest/transform/build/index.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'createScriptTransformer', { + enumerable: true, + get: function () { + return _ScriptTransformer.createScriptTransformer; + } +}); +Object.defineProperty(exports, 'createTranspilingRequire', { + enumerable: true, + get: function () { + return _ScriptTransformer.createTranspilingRequire; + } +}); +Object.defineProperty(exports, 'handlePotentialSyntaxError', { + enumerable: true, + get: function () { + return _enhanceUnexpectedTokenMessage.default; + } +}); +Object.defineProperty(exports, 'shouldInstrument', { + enumerable: true, + get: function () { + return _shouldInstrument.default; + } +}); +var _ScriptTransformer = require('./ScriptTransformer'); +var _shouldInstrument = _interopRequireDefault(require('./shouldInstrument')); +var _enhanceUnexpectedTokenMessage = _interopRequireDefault( + require('./enhanceUnexpectedTokenMessage') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} diff --git a/node_modules/@jest/transform/build/runtimeErrorsAndWarnings.js b/node_modules/@jest/transform/build/runtimeErrorsAndWarnings.js new file mode 100644 index 0000000..d5e78ed --- /dev/null +++ b/node_modules/@jest/transform/build/runtimeErrorsAndWarnings.js @@ -0,0 +1,94 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.makeInvalidTransformerError = + exports.makeInvalidSyncTransformerError = + exports.makeInvalidSourceMapWarning = + exports.makeInvalidReturnValueError = + void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _slash() { + const data = _interopRequireDefault(require('slash')); + _slash = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const BULLET = '\u25cf '; +const DOCUMENTATION_NOTE = ` ${_chalk().default.bold( + 'Code Transformation Documentation:' +)} + https://jestjs.io/docs/code-transformation +`; +const UPGRADE_NOTE = ` ${_chalk().default.bold( + 'This error may be caused by a breaking change in Jest 28:' +)} + https://jestjs.io/docs/28.x/upgrading-to-jest28#transformer +`; +const makeInvalidReturnValueError = transformPath => + _chalk().default.red( + [ + _chalk().default.bold(`${BULLET}Invalid return value:`), + ' `process()` or/and `processAsync()` method of code transformer found at ', + ` "${(0, _slash().default)(transformPath)}" `, + ' should return an object or a Promise resolving to an object. The object ', + ' must have `code` property with a string of processed code.', + '' + ].join('\n') + + UPGRADE_NOTE + + DOCUMENTATION_NOTE + ); +exports.makeInvalidReturnValueError = makeInvalidReturnValueError; +const makeInvalidSourceMapWarning = (filename, transformPath) => + _chalk().default.yellow( + [ + _chalk().default.bold(`${BULLET}Invalid source map:`), + ` The source map for "${(0, _slash().default)( + filename + )}" returned by "${(0, _slash().default)(transformPath)}" is invalid.`, + ' Proceeding without source mapping for that file.' + ].join('\n') + ); +exports.makeInvalidSourceMapWarning = makeInvalidSourceMapWarning; +const makeInvalidSyncTransformerError = transformPath => + _chalk().default.red( + [ + _chalk().default.bold(`${BULLET}Invalid synchronous transformer module:`), + ` "${(0, _slash().default)( + transformPath + )}" specified in the "transform" object of Jest configuration`, + ' must export a `process` function.', + '' + ].join('\n') + DOCUMENTATION_NOTE + ); +exports.makeInvalidSyncTransformerError = makeInvalidSyncTransformerError; +const makeInvalidTransformerError = transformPath => + _chalk().default.red( + [ + _chalk().default.bold(`${BULLET}Invalid transformer module:`), + ` "${(0, _slash().default)( + transformPath + )}" specified in the "transform" object of Jest configuration`, + ' must export a `process` or `processAsync` or `createTransformer` function.', + '' + ].join('\n') + DOCUMENTATION_NOTE + ); +exports.makeInvalidTransformerError = makeInvalidTransformerError; diff --git a/node_modules/@jest/transform/build/shouldInstrument.js b/node_modules/@jest/transform/build/shouldInstrument.js new file mode 100644 index 0000000..3c71c47 --- /dev/null +++ b/node_modules/@jest/transform/build/shouldInstrument.js @@ -0,0 +1,167 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = shouldInstrument; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _micromatch() { + const data = _interopRequireDefault(require('micromatch')); + _micromatch = function () { + return data; + }; + return data; +} +function _jestRegexUtil() { + const data = require('jest-regex-util'); + _jestRegexUtil = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const MOCKS_PATTERN = new RegExp( + (0, _jestRegexUtil().escapePathForRegex)( + `${path().sep}__mocks__${path().sep}` + ) +); +const cachedRegexes = new Map(); +const getRegex = regexStr => { + if (!cachedRegexes.has(regexStr)) { + cachedRegexes.set(regexStr, new RegExp(regexStr)); + } + const regex = cachedRegexes.get(regexStr); + + // prevent stateful regexes from breaking, just in case + regex.lastIndex = 0; + return regex; +}; +function shouldInstrument(filename, options, config) { + if (!options.collectCoverage) { + return false; + } + if ( + config.forceCoverageMatch.length && + _micromatch().default.any(filename, config.forceCoverageMatch) + ) { + return true; + } + if ( + !config.testPathIgnorePatterns.some(pattern => + getRegex(pattern).test(filename) + ) + ) { + if (config.testRegex.some(regex => new RegExp(regex).test(filename))) { + return false; + } + if ( + (0, _jestUtil().globsToMatcher)(config.testMatch)( + (0, _jestUtil().replacePathSepForGlob)(filename) + ) + ) { + return false; + } + } + if ( + // still cover if `only` is specified + options.collectCoverageFrom.length && + !(0, _jestUtil().globsToMatcher)(options.collectCoverageFrom)( + (0, _jestUtil().replacePathSepForGlob)( + path().relative(config.rootDir, filename) + ) + ) + ) { + return false; + } + if ( + config.coveragePathIgnorePatterns.some(pattern => !!filename.match(pattern)) + ) { + return false; + } + if (config.globalSetup === filename) { + return false; + } + if (config.globalTeardown === filename) { + return false; + } + if (config.setupFiles.includes(filename)) { + return false; + } + if (config.setupFilesAfterEnv.includes(filename)) { + return false; + } + if (MOCKS_PATTERN.test(filename)) { + return false; + } + if (options.changedFiles && !options.changedFiles.has(filename)) { + if (!options.sourcesRelatedToTestsInChangedFiles) { + return false; + } + if (!options.sourcesRelatedToTestsInChangedFiles.has(filename)) { + return false; + } + } + return true; +} diff --git a/node_modules/@jest/transform/build/types.js b/node_modules/@jest/transform/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/transform/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/transform/package.json b/node_modules/@jest/transform/package.json new file mode 100644 index 0000000..b31bfc1 --- /dev/null +++ b/node_modules/@jest/transform/package.json @@ -0,0 +1,52 @@ +{ + "name": "@jest/transform", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-transform" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/types": "^29.2.1", + "@jridgewell/trace-mapping": "^0.3.15", + "babel-plugin-istanbul": "^6.1.1", + "chalk": "^4.0.0", + "convert-source-map": "^1.4.0", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.2.1", + "jest-regex-util": "^29.2.0", + "jest-util": "^29.2.1", + "micromatch": "^4.0.4", + "pirates": "^4.0.4", + "slash": "^3.0.0", + "write-file-atomic": "^4.0.1" + }, + "devDependencies": { + "@jest/test-utils": "^29.2.1", + "@types/babel__core": "^7.1.14", + "@types/convert-source-map": "^1.5.1", + "@types/graceful-fs": "^4.1.3", + "@types/micromatch": "^4.0.1", + "@types/write-file-atomic": "^4.0.0", + "dedent": "^0.7.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/@jest/types/LICENSE b/node_modules/@jest/types/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/@jest/types/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jest/types/README.md b/node_modules/@jest/types/README.md new file mode 100644 index 0000000..a4f56b6 --- /dev/null +++ b/node_modules/@jest/types/README.md @@ -0,0 +1,30 @@ +# @jest/types + +This package contains shared types of Jest's packages. + +If you are looking for types of [Jest globals](https://jestjs.io/docs/api), you can import them from `@jest/globals` package: + +```ts +import {describe, expect, it} from '@jest/globals'; + +describe('my tests', () => { + it('works', () => { + expect(1).toBe(1); + }); +}); +``` + +If you prefer to omit imports, a similar result can be achieved installing the [@types/jest](https://npmjs.com/package/@types/jest) package. Note that this is a third party library maintained at [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest) and may not cover the latest Jest features. + +Another use-case for `@types/jest` is a typed Jest config as those types are not provided by Jest out of the box: + +```ts +// jest.config.ts +import {Config} from '@jest/types'; + +const config: Config.InitialOptions = { + // some typed config +}; + +export default config; +``` diff --git a/node_modules/@jest/types/build/Circus.js b/node_modules/@jest/types/build/Circus.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/types/build/Circus.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/types/build/Config.js b/node_modules/@jest/types/build/Config.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/types/build/Config.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/types/build/Global.js b/node_modules/@jest/types/build/Global.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/types/build/Global.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/types/build/TestResult.js b/node_modules/@jest/types/build/TestResult.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/types/build/TestResult.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/types/build/Transform.js b/node_modules/@jest/types/build/Transform.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/types/build/Transform.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/types/build/index.d.ts b/node_modules/@jest/types/build/index.d.ts new file mode 100644 index 0000000..d20c938 --- /dev/null +++ b/node_modules/@jest/types/build/index.d.ts @@ -0,0 +1,1168 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import type {Arguments} from 'yargs'; +import type {CoverageMapData} from 'istanbul-lib-coverage'; +import type {ForegroundColor} from 'chalk'; +import type {ReportOptions} from 'istanbul-reports'; +import type {SnapshotFormat} from '@jest/schemas'; + +declare type Argv = Arguments< + Partial<{ + all: boolean; + automock: boolean; + bail: boolean | number; + cache: boolean; + cacheDirectory: string; + changedFilesWithAncestor: boolean; + changedSince: string; + ci: boolean; + clearCache: boolean; + clearMocks: boolean; + collectCoverage: boolean; + collectCoverageFrom: string; + color: boolean; + colors: boolean; + config: string; + coverage: boolean; + coverageDirectory: string; + coveragePathIgnorePatterns: Array; + coverageReporters: Array; + coverageThreshold: string; + debug: boolean; + env: string; + expand: boolean; + findRelatedTests: boolean; + forceExit: boolean; + globals: string; + globalSetup: string | null | undefined; + globalTeardown: string | null | undefined; + haste: string; + ignoreProjects: Array; + init: boolean; + injectGlobals: boolean; + json: boolean; + lastCommit: boolean; + logHeapUsage: boolean; + maxWorkers: number | string; + moduleDirectories: Array; + moduleFileExtensions: Array; + moduleNameMapper: string; + modulePathIgnorePatterns: Array; + modulePaths: Array; + noStackTrace: boolean; + notify: boolean; + notifyMode: string; + onlyChanged: boolean; + onlyFailures: boolean; + outputFile: string; + preset: string | null | undefined; + prettierPath: string | null | undefined; + projects: Array; + reporters: Array; + resetMocks: boolean; + resetModules: boolean; + resolver: string | null | undefined; + restoreMocks: boolean; + rootDir: string; + roots: Array; + runInBand: boolean; + seed: number; + showSeed: boolean; + selectProjects: Array; + setupFiles: Array; + setupFilesAfterEnv: Array; + shard: string; + showConfig: boolean; + silent: boolean; + snapshotSerializers: Array; + testEnvironment: string; + testEnvironmentOptions: string; + testFailureExitCode: string | null | undefined; + testMatch: Array; + testNamePattern: string; + testPathIgnorePatterns: Array; + testPathPattern: Array; + testRegex: string | Array; + testResultsProcessor: string; + testRunner: string; + testSequencer: string; + testTimeout: number | null | undefined; + transform: string; + transformIgnorePatterns: Array; + unmockedModulePathPatterns: Array | null | undefined; + updateSnapshot: boolean; + useStderr: boolean; + verbose: boolean; + version: boolean; + watch: boolean; + watchAll: boolean; + watchman: boolean; + watchPathIgnorePatterns: Array; + workerIdleMemoryLimit: number | string; + }> +>; + +declare type ArrayTable = Table | Row; + +declare type AssertionResult = { + ancestorTitles: Array; + duration?: number | null; + failureDetails: Array; + failureMessages: Array; + fullName: string; + invocations?: number; + location?: Callsite | null; + numPassingAsserts: number; + retryReasons?: Array; + status: Status; + title: string; +}; + +declare type AsyncEvent = + | { + name: 'setup'; + testNamePattern?: string; + runtimeGlobals: JestGlobals; + parentProcess: Process; + } + | { + name: 'include_test_location_in_result'; + } + | { + name: 'hook_start'; + hook: Hook; + } + | { + name: 'hook_success'; + describeBlock?: DescribeBlock; + test?: TestEntry; + hook: Hook; + } + | { + name: 'hook_failure'; + error: string | Exception; + describeBlock?: DescribeBlock; + test?: TestEntry; + hook: Hook; + } + | { + name: 'test_fn_start'; + test: TestEntry; + } + | { + name: 'test_fn_success'; + test: TestEntry; + } + | { + name: 'test_fn_failure'; + error: Exception; + test: TestEntry; + } + | { + name: 'test_retry'; + test: TestEntry; + } + | { + name: 'test_start'; + test: TestEntry; + } + | { + name: 'test_skip'; + test: TestEntry; + } + | { + name: 'test_todo'; + test: TestEntry; + } + | { + name: 'test_done'; + test: TestEntry; + } + | { + name: 'run_describe_start'; + describeBlock: DescribeBlock; + } + | { + name: 'run_describe_finish'; + describeBlock: DescribeBlock; + } + | { + name: 'run_start'; + } + | { + name: 'run_finish'; + } + | { + name: 'teardown'; + }; + +declare type AsyncFn = TestFn_2 | HookFn_2; + +declare type BlockFn = () => void; + +declare type BlockFn_2 = Global.BlockFn; + +declare type BlockMode = void | 'skip' | 'only' | 'todo'; + +declare type BlockName = string; + +declare type BlockName_2 = Global.BlockName; + +declare type BlockNameLike = BlockName | NameLike; + +declare type BlockNameLike_2 = Global.BlockNameLike; + +declare type Callsite = { + column: number; + line: number; +}; + +declare namespace Circus { + export { + DoneFn, + BlockFn_2 as BlockFn, + BlockName_2 as BlockName, + BlockNameLike_2 as BlockNameLike, + BlockMode, + TestMode, + TestName_2 as TestName, + TestNameLike_2 as TestNameLike, + TestFn_2 as TestFn, + ConcurrentTestFn_2 as ConcurrentTestFn, + HookFn_2 as HookFn, + AsyncFn, + SharedHookType, + HookType, + TestContext_2 as TestContext, + Exception, + FormattedError, + Hook, + EventHandler, + Event_2 as Event, + SyncEvent, + AsyncEvent, + MatcherResults, + TestStatus, + TestResult_2 as TestResult, + RunResult, + TestResults, + GlobalErrorHandlers, + State, + DescribeBlock, + TestError, + TestEntry, + }; +} +export {Circus}; + +declare type Col = unknown; + +declare type ConcurrentTestFn = () => TestReturnValuePromise; + +declare type ConcurrentTestFn_2 = Global.ConcurrentTestFn; + +declare namespace Config { + export { + FakeableAPI, + GlobalFakeTimersConfig, + FakeTimersConfig, + LegacyFakeTimersConfig, + HasteConfig, + CoverageReporterName, + CoverageReporterWithOptions, + CoverageReporters, + ReporterConfig, + TransformerConfig, + ConfigGlobals, + DefaultOptions, + DisplayName, + InitialOptionsWithRootDir, + InitialProjectOptions, + InitialOptions, + SnapshotUpdateState, + CoverageThresholdValue, + GlobalConfig, + ProjectConfig, + Argv, + }; +} +export {Config}; + +declare interface ConfigGlobals { + [K: string]: unknown; +} + +declare type CoverageProvider = 'babel' | 'v8'; + +declare type CoverageReporterName = keyof ReportOptions; + +declare type CoverageReporters = Array< + CoverageReporterName | CoverageReporterWithOptions +>; + +declare type CoverageReporterWithOptions = + K extends CoverageReporterName + ? ReportOptions[K] extends never + ? never + : [K, Partial] + : never; + +declare type CoverageThreshold = { + [path: string]: CoverageThresholdValue; + global: CoverageThresholdValue; +}; + +declare type CoverageThresholdValue = { + branches?: number; + functions?: number; + lines?: number; + statements?: number; +}; + +declare type DefaultOptions = { + automock: boolean; + bail: number; + cache: boolean; + cacheDirectory: string; + changedFilesWithAncestor: boolean; + ci: boolean; + clearMocks: boolean; + collectCoverage: boolean; + coveragePathIgnorePatterns: Array; + coverageReporters: Array; + coverageProvider: CoverageProvider; + detectLeaks: boolean; + detectOpenHandles: boolean; + errorOnDeprecated: boolean; + expand: boolean; + extensionsToTreatAsEsm: Array; + fakeTimers: FakeTimers; + forceCoverageMatch: Array; + globals: ConfigGlobals; + haste: HasteConfig; + injectGlobals: boolean; + listTests: boolean; + maxConcurrency: number; + maxWorkers: number | string; + moduleDirectories: Array; + moduleFileExtensions: Array; + moduleNameMapper: Record>; + modulePathIgnorePatterns: Array; + noStackTrace: boolean; + notify: boolean; + notifyMode: NotifyMode; + passWithNoTests: boolean; + prettierPath: string; + resetMocks: boolean; + resetModules: boolean; + restoreMocks: boolean; + roots: Array; + runTestsByPath: boolean; + runner: string; + setupFiles: Array; + setupFilesAfterEnv: Array; + skipFilter: boolean; + slowTestThreshold: number; + snapshotFormat: SnapshotFormat; + snapshotSerializers: Array; + testEnvironment: string; + testEnvironmentOptions: Record; + testFailureExitCode: string | number; + testLocationInResults: boolean; + testMatch: Array; + testPathIgnorePatterns: Array; + testRegex: Array; + testRunner: string; + testSequencer: string; + transformIgnorePatterns: Array; + useStderr: boolean; + watch: boolean; + watchPathIgnorePatterns: Array; + watchman: boolean; +}; + +declare interface Describe extends DescribeBase { + only: DescribeBase; + skip: DescribeBase; +} + +declare interface DescribeBase { + (blockName: BlockNameLike, blockFn: BlockFn): void; + each: Each; +} + +declare type DescribeBlock = { + type: 'describeBlock'; + children: Array; + hooks: Array; + mode: BlockMode; + name: BlockName_2; + parent?: DescribeBlock; + /** @deprecated Please get from `children` array instead */ + tests: Array; +}; + +declare type DisplayName = { + name: string; + color: typeof ForegroundColor; +}; + +declare type DoneFn = Global.DoneFn; + +declare type DoneFn_2 = (reason?: string | Error) => void; + +declare type DoneTakingTestFn = ( + this: TestContext, + done: DoneFn_2, +) => ValidTestReturnValues; + +declare interface Each { + >(table: ReadonlyArray): ( + name: string | NameLike, + fn: (arg: T) => ReturnType, + timeout?: number, + ) => void; + ]>(table: ReadonlyArray): ( + name: string | NameLike, + fn: (...args: T) => ReturnType, + timeout?: number, + ) => void; + >(table: ReadonlyArray): ( + name: string | NameLike, + fn: (...args: T) => ReturnType, + timeout?: number, + ) => void; + (table: ReadonlyArray): ( + name: string | NameLike, + fn: (arg: T) => ReturnType, + timeout?: number, + ) => void; + (strings: TemplateStringsArray, ...expressions: Array): ( + name: string | NameLike, + fn: (arg: Record) => ReturnType, + timeout?: number, + ) => void; + >( + strings: TemplateStringsArray, + ...expressions: Array + ): ( + name: string | NameLike, + fn: (arg: T) => ReturnType, + timeout?: number, + ) => void; +} + +declare type EachTable = ArrayTable | TemplateTable; + +declare type EachTestFn = ( + ...args: ReadonlyArray +) => ReturnType; + +declare type Event_2 = SyncEvent | AsyncEvent; + +declare interface EventHandler { + (event: AsyncEvent, state: State): void | Promise; + (event: SyncEvent, state: State): void; +} + +declare type Exception = any; + +declare interface Failing { + (testName: TestNameLike, fn: T, timeout?: number): void; + each: Each; +} + +declare type FakeableAPI = + | 'Date' + | 'hrtime' + | 'nextTick' + | 'performance' + | 'queueMicrotask' + | 'requestAnimationFrame' + | 'cancelAnimationFrame' + | 'requestIdleCallback' + | 'cancelIdleCallback' + | 'setImmediate' + | 'clearImmediate' + | 'setInterval' + | 'clearInterval' + | 'setTimeout' + | 'clearTimeout'; + +declare type FakeTimers = GlobalFakeTimersConfig & + ( + | (FakeTimersConfig & { + now?: Exclude; + }) + | LegacyFakeTimersConfig + ); + +declare type FakeTimersConfig = { + /** + * If set to `true` all timers will be advanced automatically + * by 20 milliseconds every 20 milliseconds. A custom time delta + * may be provided by passing a number. + * + * @defaultValue + * The default is `false`. + */ + advanceTimers?: boolean | number; + /** + * List of names of APIs (e.g. `Date`, `nextTick()`, `setImmediate()`, + * `setTimeout()`) that should not be faked. + * + * @defaultValue + * The default is `[]`, meaning all APIs are faked. + */ + doNotFake?: Array; + /** + * Sets current system time to be used by fake timers. + * + * @defaultValue + * The default is `Date.now()`. + */ + now?: number | Date; + /** + * The maximum number of recursive timers that will be run when calling + * `jest.runAllTimers()`. + * + * @defaultValue + * The default is `100_000` timers. + */ + timerLimit?: number; + /** + * Use the old fake timers implementation instead of one backed by + * [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers). + * + * @defaultValue + * The default is `false`. + */ + legacyFakeTimers?: false; +}; + +declare type FormattedError = string; + +declare type GeneratorReturningTestFn = ( + this: TestContext, +) => TestReturnValueGenerator; + +declare namespace Global { + export { + ValidTestReturnValues, + TestReturnValue, + TestContext, + DoneFn_2 as DoneFn, + DoneTakingTestFn, + PromiseReturningTestFn, + GeneratorReturningTestFn, + NameLike, + TestName, + TestNameLike, + TestFn, + ConcurrentTestFn, + BlockFn, + BlockName, + BlockNameLike, + HookFn, + Col, + Row, + Table, + ArrayTable, + TemplateTable, + TemplateData, + EachTable, + TestCallback, + EachTestFn, + HookBase, + Failing, + ItBase, + It, + ItConcurrentBase, + ItConcurrentExtended, + ItConcurrent, + DescribeBase, + Describe, + TestFrameworkGlobals, + GlobalAdditions, + Global_2 as Global, + }; +} +export {Global}; + +declare interface Global_2 + extends GlobalAdditions, + Omit { + [extras: PropertyKey]: unknown; +} + +declare interface GlobalAdditions extends TestFrameworkGlobals { + __coverage__: CoverageMapData; +} + +declare type GlobalConfig = { + bail: number; + changedSince?: string; + changedFilesWithAncestor: boolean; + ci: boolean; + collectCoverage: boolean; + collectCoverageFrom: Array; + coverageDirectory: string; + coveragePathIgnorePatterns?: Array; + coverageProvider: CoverageProvider; + coverageReporters: CoverageReporters; + coverageThreshold?: CoverageThreshold; + detectLeaks: boolean; + detectOpenHandles: boolean; + expand: boolean; + filter?: string; + findRelatedTests: boolean; + forceExit: boolean; + json: boolean; + globalSetup?: string; + globalTeardown?: string; + lastCommit: boolean; + logHeapUsage: boolean; + listTests: boolean; + maxConcurrency: number; + maxWorkers: number; + noStackTrace: boolean; + nonFlagArgs: Array; + noSCM?: boolean; + notify: boolean; + notifyMode: NotifyMode; + outputFile?: string; + onlyChanged: boolean; + onlyFailures: boolean; + passWithNoTests: boolean; + projects: Array; + replname?: string; + reporters?: Array; + runTestsByPath: boolean; + rootDir: string; + seed: number; + showSeed?: boolean; + shard?: ShardConfig; + silent?: boolean; + skipFilter: boolean; + snapshotFormat: SnapshotFormat; + errorOnDeprecated: boolean; + testFailureExitCode: number; + testNamePattern?: string; + testPathPattern: string; + testResultsProcessor?: string; + testSequencer: string; + testTimeout?: number; + updateSnapshot: SnapshotUpdateState; + useStderr: boolean; + verbose?: boolean; + watch: boolean; + watchAll: boolean; + watchman: boolean; + watchPlugins?: Array<{ + path: string; + config: Record; + }> | null; + workerIdleMemoryLimit?: number; +}; + +declare type GlobalErrorHandlers = { + uncaughtException: Array<(exception: Exception) => void>; + unhandledRejection: Array< + (exception: Exception, promise: Promise) => void + >; +}; + +declare type GlobalFakeTimersConfig = { + /** + * Whether fake timers should be enabled globally for all test files. + * + * @defaultValue + * The default is `false`. + */ + enableGlobally?: boolean; +}; + +declare type HasteConfig = { + /** Whether to hash files using SHA-1. */ + computeSha1?: boolean; + /** The platform to use as the default, e.g. 'ios'. */ + defaultPlatform?: string | null; + /** Force use of Node's `fs` APIs rather than shelling out to `find` */ + forceNodeFilesystemAPI?: boolean; + /** + * Whether to follow symlinks when crawling for files. + * This options cannot be used in projects which use watchman. + * Projects with `watchman` set to true will error if this option is set to true. + */ + enableSymlinks?: boolean; + /** string to a custom implementation of Haste. */ + hasteImplModulePath?: string; + /** All platforms to target, e.g ['ios', 'android']. */ + platforms?: Array; + /** Whether to throw on error on module collision. */ + throwOnModuleCollision?: boolean; + /** Custom HasteMap module */ + hasteMapModulePath?: string; + /** Whether to retain all files, allowing e.g. search for tests in `node_modules`. */ + retainAllFiles?: boolean; +}; + +declare type Hook = { + asyncError: Error; + fn: HookFn_2; + type: HookType; + parent: DescribeBlock; + seenDone: boolean; + timeout: number | undefined | null; +}; + +declare interface HookBase { + (fn: HookFn, timeout?: number): void; +} + +declare type HookFn = TestFn; + +declare type HookFn_2 = Global.HookFn; + +declare type HookType = SharedHookType | 'afterEach' | 'beforeEach'; + +declare type InitialOptions = Partial<{ + automock: boolean; + bail: boolean | number; + cache: boolean; + cacheDirectory: string; + ci: boolean; + clearMocks: boolean; + changedFilesWithAncestor: boolean; + changedSince: string; + collectCoverage: boolean; + collectCoverageFrom: Array; + coverageDirectory: string; + coveragePathIgnorePatterns: Array; + coverageProvider: CoverageProvider; + coverageReporters: CoverageReporters; + coverageThreshold: CoverageThreshold; + dependencyExtractor: string; + detectLeaks: boolean; + detectOpenHandles: boolean; + displayName: string | DisplayName; + expand: boolean; + extensionsToTreatAsEsm: Array; + fakeTimers: FakeTimers; + filter: string; + findRelatedTests: boolean; + forceCoverageMatch: Array; + forceExit: boolean; + json: boolean; + globals: ConfigGlobals; + globalSetup: string | null | undefined; + globalTeardown: string | null | undefined; + haste: HasteConfig; + id: string; + injectGlobals: boolean; + reporters: Array; + logHeapUsage: boolean; + lastCommit: boolean; + listTests: boolean; + maxConcurrency: number; + maxWorkers: number | string; + moduleDirectories: Array; + moduleFileExtensions: Array; + moduleNameMapper: { + [key: string]: string | Array; + }; + modulePathIgnorePatterns: Array; + modulePaths: Array; + noStackTrace: boolean; + notify: boolean; + notifyMode: string; + onlyChanged: boolean; + onlyFailures: boolean; + outputFile: string; + passWithNoTests: boolean; + preset: string | null | undefined; + prettierPath: string | null | undefined; + projects: Array; + replname: string | null | undefined; + resetMocks: boolean; + resetModules: boolean; + resolver: string | null | undefined; + restoreMocks: boolean; + rootDir: string; + roots: Array; + runner: string; + runTestsByPath: boolean; + runtime: string; + sandboxInjectedGlobals: Array; + setupFiles: Array; + setupFilesAfterEnv: Array; + showSeed: boolean; + silent: boolean; + skipFilter: boolean; + skipNodeResolution: boolean; + slowTestThreshold: number; + snapshotResolver: string; + snapshotSerializers: Array; + snapshotFormat: SnapshotFormat; + errorOnDeprecated: boolean; + testEnvironment: string; + testEnvironmentOptions: Record; + testFailureExitCode: string | number; + testLocationInResults: boolean; + testMatch: Array; + testNamePattern: string; + testPathIgnorePatterns: Array; + testRegex: string | Array; + testResultsProcessor: string; + testRunner: string; + testSequencer: string; + testTimeout: number; + transform: { + [regex: string]: string | TransformerConfig; + }; + transformIgnorePatterns: Array; + watchPathIgnorePatterns: Array; + unmockedModulePathPatterns: Array; + updateSnapshot: boolean; + useStderr: boolean; + verbose?: boolean; + watch: boolean; + watchAll: boolean; + watchman: boolean; + watchPlugins: Array]>; + workerIdleMemoryLimit: number | string; +}>; + +declare type InitialOptionsWithRootDir = InitialOptions & + Required>; + +declare type InitialProjectOptions = Pick< + InitialOptions & { + cwd?: string; + }, + keyof ProjectConfig +>; + +declare interface It extends ItBase { + only: ItBase; + skip: ItBase; + todo: (testName: TestNameLike) => void; +} + +declare interface ItBase { + (testName: TestNameLike, fn: TestFn, timeout?: number): void; + each: Each; + failing: Failing; +} + +declare interface ItConcurrent extends It { + concurrent: ItConcurrentExtended; +} + +declare interface ItConcurrentBase { + (testName: TestNameLike, testFn: ConcurrentTestFn, timeout?: number): void; + each: Each; + failing: Failing; +} + +declare interface ItConcurrentExtended extends ItConcurrentBase { + only: ItConcurrentBase; + skip: ItConcurrentBase; +} + +declare interface JestGlobals extends Global.TestFrameworkGlobals { + expect: unknown; +} + +declare type LegacyFakeTimersConfig = { + /** + * Use the old fake timers implementation instead of one backed by + * [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers). + * + * @defaultValue + * The default is `false`. + */ + legacyFakeTimers?: true; +}; + +declare type MatcherResults = { + actual: unknown; + expected: unknown; + name: string; + pass: boolean; +}; + +declare type NameLike = number | Function; + +declare type NotifyMode = + | 'always' + | 'failure' + | 'success' + | 'change' + | 'success-change' + | 'failure-change'; + +declare type Process = NodeJS.Process; + +declare type ProjectConfig = { + automock: boolean; + cache: boolean; + cacheDirectory: string; + clearMocks: boolean; + coveragePathIgnorePatterns: Array; + cwd: string; + dependencyExtractor?: string; + detectLeaks: boolean; + detectOpenHandles: boolean; + displayName?: DisplayName; + errorOnDeprecated: boolean; + extensionsToTreatAsEsm: Array; + fakeTimers: FakeTimers; + filter?: string; + forceCoverageMatch: Array; + globalSetup?: string; + globalTeardown?: string; + globals: ConfigGlobals; + haste: HasteConfig; + id: string; + injectGlobals: boolean; + moduleDirectories: Array; + moduleFileExtensions: Array; + moduleNameMapper: Array<[string, string]>; + modulePathIgnorePatterns: Array; + modulePaths?: Array; + prettierPath: string; + resetMocks: boolean; + resetModules: boolean; + resolver?: string; + restoreMocks: boolean; + rootDir: string; + roots: Array; + runner: string; + runtime?: string; + sandboxInjectedGlobals: Array; + setupFiles: Array; + setupFilesAfterEnv: Array; + skipFilter: boolean; + skipNodeResolution?: boolean; + slowTestThreshold: number; + snapshotResolver?: string; + snapshotSerializers: Array; + snapshotFormat: SnapshotFormat; + testEnvironment: string; + testEnvironmentOptions: Record; + testMatch: Array; + testLocationInResults: boolean; + testPathIgnorePatterns: Array; + testRegex: Array; + testRunner: string; + transform: Array<[string, string, Record]>; + transformIgnorePatterns: Array; + watchPathIgnorePatterns: Array; + unmockedModulePathPatterns?: Array; + workerIdleMemoryLimit?: number; +}; + +declare type PromiseReturningTestFn = (this: TestContext) => TestReturnValue; + +declare type ReporterConfig = [string, Record]; + +declare type Row = ReadonlyArray; + +declare type RunResult = { + unhandledErrors: Array; + testResults: TestResults; +}; + +declare type SerializableError = { + code?: unknown; + message: string; + stack: string | null | undefined; + type?: string; +}; + +declare type ShardConfig = { + shardIndex: number; + shardCount: number; +}; + +declare type SharedHookType = 'afterAll' | 'beforeAll'; + +declare type SnapshotUpdateState = 'all' | 'new' | 'none'; + +declare type State = { + currentDescribeBlock: DescribeBlock; + currentlyRunningTest?: TestEntry | null; + expand?: boolean; + hasFocusedTests: boolean; + hasStarted: boolean; + originalGlobalErrorHandlers?: GlobalErrorHandlers; + parentProcess: Process | null; + rootDescribeBlock: DescribeBlock; + testNamePattern?: RegExp | null; + testTimeout: number; + unhandledErrors: Array; + includeTestLocationInResult: boolean; + maxConcurrency: number; +}; + +declare type Status = + | 'passed' + | 'failed' + | 'skipped' + | 'pending' + | 'todo' + | 'disabled'; + +declare type SyncEvent = + | { + asyncError: Error; + mode: BlockMode; + name: 'start_describe_definition'; + blockName: BlockName_2; + } + | { + mode: BlockMode; + name: 'finish_describe_definition'; + blockName: BlockName_2; + } + | { + asyncError: Error; + name: 'add_hook'; + hookType: HookType; + fn: HookFn_2; + timeout: number | undefined; + } + | { + asyncError: Error; + name: 'add_test'; + testName: TestName_2; + fn: TestFn_2; + mode?: TestMode; + concurrent: boolean; + timeout: number | undefined; + failing: boolean; + } + | { + name: 'error'; + error: Exception; + }; + +declare type Table = ReadonlyArray; + +declare type TemplateData = ReadonlyArray; + +declare type TemplateTable = TemplateStringsArray; + +declare type TestCallback = BlockFn | TestFn | ConcurrentTestFn; + +declare type TestContext = Record; + +declare type TestContext_2 = Global.TestContext; + +declare type TestEntry = { + type: 'test'; + asyncError: Exception; + errors: Array; + retryReasons: Array; + fn: TestFn_2; + invocations: number; + mode: TestMode; + concurrent: boolean; + name: TestName_2; + parent: DescribeBlock; + startedAt?: number | null; + duration?: number | null; + seenDone: boolean; + status?: TestStatus | null; + timeout?: number; + failing: boolean; +}; + +declare type TestError = Exception | [Exception | undefined, Exception]; + +declare type TestFn = + | PromiseReturningTestFn + | GeneratorReturningTestFn + | DoneTakingTestFn; + +declare type TestFn_2 = Global.TestFn; + +declare interface TestFrameworkGlobals { + it: ItConcurrent; + test: ItConcurrent; + fit: ItBase & { + concurrent?: ItConcurrentBase; + }; + xit: ItBase; + xtest: ItBase; + describe: Describe; + xdescribe: DescribeBase; + fdescribe: DescribeBase; + beforeAll: HookBase; + beforeEach: HookBase; + afterEach: HookBase; + afterAll: HookBase; +} + +declare type TestMode = BlockMode; + +declare type TestName = string; + +declare type TestName_2 = Global.TestName; + +declare type TestNameLike = TestName | NameLike; + +declare type TestNameLike_2 = Global.TestNameLike; + +declare namespace TestResult { + export {AssertionResult, SerializableError}; +} +export {TestResult}; + +declare type TestResult_2 = { + duration?: number | null; + errors: Array; + errorsDetailed: Array; + invocations: number; + status: TestStatus; + location?: { + column: number; + line: number; + } | null; + retryReasons: Array; + testPath: Array; +}; + +declare type TestResults = Array; + +declare type TestReturnValue = ValidTestReturnValues | TestReturnValuePromise; + +declare type TestReturnValueGenerator = Generator; + +declare type TestReturnValuePromise = Promise; + +declare type TestStatus = 'skip' | 'done' | 'todo'; + +declare type TransformerConfig = [string, Record]; + +declare type TransformResult = { + code: string; + originalCode: string; + sourceMapPath: string | null; +}; + +declare namespace TransformTypes { + export {TransformResult}; +} +export {TransformTypes}; + +declare type ValidTestReturnValues = void | undefined; + +export {}; diff --git a/node_modules/@jest/types/build/index.js b/node_modules/@jest/types/build/index.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/@jest/types/build/index.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/@jest/types/package.json b/node_modules/@jest/types/package.json new file mode 100644 index 0000000..5909460 --- /dev/null +++ b/node_modules/@jest/types/package.json @@ -0,0 +1,38 @@ +{ + "name": "@jest/types", + "version": "29.2.1", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-types" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/schemas": "^29.0.0", + "@types/istanbul-lib-coverage": "^2.0.0", + "@types/istanbul-reports": "^3.0.0", + "@types/node": "*", + "@types/yargs": "^17.0.8", + "chalk": "^4.0.0" + }, + "devDependencies": { + "@tsd/typescript": "~4.8.2", + "tsd-lite": "^0.6.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "4551c0fdd4d25b7206824957c7bcc6baf61e63bf" +} diff --git a/node_modules/@jridgewell/gen-mapping/LICENSE b/node_modules/@jridgewell/gen-mapping/LICENSE new file mode 100644 index 0000000..352f071 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jridgewell/gen-mapping/README.md b/node_modules/@jridgewell/gen-mapping/README.md new file mode 100644 index 0000000..c9f09b3 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/README.md @@ -0,0 +1,128 @@ +# @jridgewell/gen-mapping + +> Generate source maps + +`gen-mapping` allows you to generate a source map during transpilation or minification. +With a source map, you're able to trace the original location in the source file, either in Chrome's +DevTools or using a library like [`@jridgewell/trace-mapping`][trace-mapping]. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapGenerator`. This +provides the same `addMapping` and `setSourceContent` API. + +## Installation + +```sh +npm install @jridgewell/gen-mapping +``` + +## Usage + +```typescript +import { GenMapping, addMapping, setSourceContent, encodedMap } from '@jridgewell/gen-mapping'; + +const map = new GenMapping({ + file: 'output.js', + sourceRoot: 'https://example.com/', +}); + +setSourceContent(map, 'input.js', `function foo() {}`); + +addMapping(map, { + // Lines start at line 1, columns at column 0. + generated: { line: 1, column: 0 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +addMapping(map, { + generated: { line: 1, column: 9 }, + source: 'input.js', + original: { line: 1, column: 9 }, + name: 'foo', +}); + +assert.deepEqual(encodedMap(map), { + version: 3, + file: 'output.js', + names: ['foo'], + sourceRoot: 'https://example.com/', + sources: ['input.js'], + sourcesContent: ['function foo() {}'], + mappings: 'AAAA,SAASA', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map +gen-mapping: addSegment x 462 ops/sec ±1.53% (91 runs sampled) +gen-mapping: addMapping x 471 ops/sec ±0.77% (93 runs sampled) +source-map-js: addMapping x 178 ops/sec ±1.14% (84 runs sampled) +source-map-0.6.1: addMapping x 178 ops/sec ±1.21% (84 runs sampled) +source-map-0.8.0: addMapping x 177 ops/sec ±1.21% (83 runs sampled) +Fastest is gen-mapping: addMapping,gen-mapping: addSegment + +gen-mapping: decoded output x 157,499,812 ops/sec ±0.25% (100 runs sampled) +gen-mapping: encoded output x 625 ops/sec ±1.95% (88 runs sampled) +source-map-js: encoded output x 162 ops/sec ±0.37% (84 runs sampled) +source-map-0.6.1: encoded output x 161 ops/sec ±0.51% (84 runs sampled) +source-map-0.8.0: encoded output x 191 ops/sec ±0.12% (90 runs sampled) +Fastest is gen-mapping: decoded output + +*** + +babel.min.js.map +gen-mapping: addSegment x 35.38 ops/sec ±4.48% (48 runs sampled) +gen-mapping: addMapping x 29.93 ops/sec ±5.03% (55 runs sampled) +source-map-js: addMapping x 22.19 ops/sec ±3.39% (41 runs sampled) +source-map-0.6.1: addMapping x 22.57 ops/sec ±2.90% (41 runs sampled) +source-map-0.8.0: addMapping x 22.73 ops/sec ±2.84% (41 runs sampled) +Fastest is gen-mapping: addSegment + +gen-mapping: decoded output x 157,767,591 ops/sec ±0.10% (99 runs sampled) +gen-mapping: encoded output x 97.06 ops/sec ±1.69% (73 runs sampled) +source-map-js: encoded output x 17.51 ops/sec ±2.27% (37 runs sampled) +source-map-0.6.1: encoded output x 17.40 ops/sec ±4.61% (35 runs sampled) +source-map-0.8.0: encoded output x 17.83 ops/sec ±4.85% (36 runs sampled) +Fastest is gen-mapping: decoded output + +*** + +preact.js.map +gen-mapping: addSegment x 13,516 ops/sec ±0.27% (98 runs sampled) +gen-mapping: addMapping x 12,117 ops/sec ±0.25% (97 runs sampled) +source-map-js: addMapping x 4,285 ops/sec ±1.53% (98 runs sampled) +source-map-0.6.1: addMapping x 4,482 ops/sec ±0.20% (100 runs sampled) +source-map-0.8.0: addMapping x 4,482 ops/sec ±0.28% (99 runs sampled) +Fastest is gen-mapping: addSegment + +gen-mapping: decoded output x 157,769,691 ops/sec ±0.06% (92 runs sampled) +gen-mapping: encoded output x 18,610 ops/sec ±1.03% (93 runs sampled) +source-map-js: encoded output x 5,397 ops/sec ±0.38% (97 runs sampled) +source-map-0.6.1: encoded output x 5,422 ops/sec ±0.16% (100 runs sampled) +source-map-0.8.0: encoded output x 5,595 ops/sec ±0.11% (100 runs sampled) +Fastest is gen-mapping: decoded output + +*** + +react.js.map +gen-mapping: addSegment x 5,058 ops/sec ±0.27% (100 runs sampled) +gen-mapping: addMapping x 4,352 ops/sec ±0.13% (97 runs sampled) +source-map-js: addMapping x 1,569 ops/sec ±0.19% (99 runs sampled) +source-map-0.6.1: addMapping x 1,550 ops/sec ±0.31% (97 runs sampled) +source-map-0.8.0: addMapping x 1,560 ops/sec ±0.18% (99 runs sampled) +Fastest is gen-mapping: addSegment + +gen-mapping: decoded output x 157,479,701 ops/sec ±0.14% (99 runs sampled) +gen-mapping: encoded output x 6,392 ops/sec ±1.03% (94 runs sampled) +source-map-js: encoded output x 2,213 ops/sec ±0.36% (99 runs sampled) +source-map-0.6.1: encoded output x 2,238 ops/sec ±0.23% (100 runs sampled) +source-map-0.8.0: encoded output x 2,304 ops/sec ±0.20% (100 runs sampled) +Fastest is gen-mapping: decoded output +``` + +[source-map]: https://www.npmjs.com/package/source-map +[trace-mapping]: https://github.com/jridgewell/trace-mapping diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs new file mode 100644 index 0000000..31f9c5c --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs @@ -0,0 +1,167 @@ +import { SetArray, put } from '@jridgewell/set-array'; +import { encode } from '@jridgewell/sourcemap-codec'; + +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +let addSegment; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +let addMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +let setSourceContent; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let decodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let encodedMap; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +let allMappings; +/** + * Provides the state to generate a sourcemap. + */ +class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + } +} +(() => { + addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name) => { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + const line = getLine(mappings, genLine); + if (source == null) { + const seg = [genColumn]; + const index = getColumnIndex(line, genColumn, seg); + return insert(line, index, seg); + } + const sourcesIndex = put(sources, source); + const seg = name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, put(names, name)] + : [genColumn, sourcesIndex, sourceLine, sourceColumn]; + const index = getColumnIndex(line, genColumn, seg); + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = null; + insert(line, index, seg); + }; + addMapping = (map, mapping) => { + const { generated, source, original, name } = mapping; + return addSegment(map, generated.line - 1, generated.column, source, original == null ? undefined : original.line - 1, original === null || original === void 0 ? void 0 : original.column, name); + }; + setSourceContent = (map, source, content) => { + const { _sources: sources, _sourcesContent: sourcesContent } = map; + sourcesContent[put(sources, source)] = content; + }; + decodedMap = (map) => { + const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + return { + version: 3, + file, + names: names.array, + sourceRoot: sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + }; + }; + encodedMap = (map) => { + const decoded = decodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) }); + }; + allMappings = (map) => { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = map; + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[0] }; + let source = undefined; + let original = undefined; + let name = undefined; + if (seg.length !== 1) { + source = sources.array[seg[1]]; + original = { line: seg[2] + 1, column: seg[3] }; + if (seg.length === 5) + name = names.array[seg[4]]; + } + out.push({ generated, source, original, name }); + } + } + return out; + }; +})(); +function getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; +} +function getColumnIndex(line, column, seg) { + let index = line.length; + for (let i = index - 1; i >= 0; i--, index--) { + const current = line[i]; + const col = current[0]; + if (col > column) + continue; + if (col < column) + break; + const cmp = compare(current, seg); + if (cmp === 0) + return index; + if (cmp < 0) + break; + } + return index; +} +function compare(a, b) { + let cmp = compareNum(a.length, b.length); + if (cmp !== 0) + return cmp; + // We've already checked genColumn + if (a.length === 1) + return 0; + cmp = compareNum(a[1], b[1]); + if (cmp !== 0) + return cmp; + cmp = compareNum(a[2], b[2]); + if (cmp !== 0) + return cmp; + cmp = compareNum(a[3], b[3]); + if (cmp !== 0) + return cmp; + if (a.length === 4) + return 0; + return compareNum(a[4], b[4]); +} +function compareNum(a, b) { + return a - b; +} +function insert(array, index, value) { + if (index === -1) + return; + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} + +export { GenMapping, addMapping, addSegment, allMappings, decodedMap, encodedMap, setSourceContent }; +//# sourceMappingURL=gen-mapping.mjs.map diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map new file mode 100644 index 0000000..ed462b5 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.mjs","sources":["../../src/gen-mapping.ts"],"sourcesContent":["import { SetArray, put } from '@jridgewell/set-array';\nimport { encode } from '@jridgewell/sourcemap-codec';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\nimport type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';\n\nexport type { DecodedSourceMap, EncodedSourceMap, Mapping };\n\nexport type Options = {\n file?: string | null;\n sourceRoot?: string | null;\n};\n\n/**\n * A low-level API to associate a generated position with an original source position. Line and\n * column here are 0-based, unlike `addMapping`.\n */\nexport let addSegment: {\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: null,\n sourceLine?: null,\n sourceColumn?: null,\n name?: null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name?: null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name: string,\n ): void;\n};\n\n/**\n * A high-level API to associate a generated position with an original source position. Line is\n * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.\n */\nexport let addMapping: {\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: null;\n original?: null;\n name?: null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name?: null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name: string;\n },\n ): void;\n};\n\n/**\n * Adds/removes the content of the source file to the source map.\n */\nexport let setSourceContent: (map: GenMapping, source: string, content: string | null) => void;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let decodedMap: (map: GenMapping) => DecodedSourceMap;\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let encodedMap: (map: GenMapping) => EncodedSourceMap;\n\n/**\n * Returns an array of high-level mapping objects for every recorded segment, which could then be\n * passed to the `source-map` library.\n */\nexport let allMappings: (map: GenMapping) => Mapping[];\n\n/**\n * Provides the state to generate a sourcemap.\n */\nexport class GenMapping {\n private _names = new SetArray();\n private _sources = new SetArray();\n private _sourcesContent: (string | null)[] = [];\n private _mappings: SourceMapSegment[][] = [];\n declare file: string | null | undefined;\n declare sourceRoot: string | null | undefined;\n\n constructor({ file, sourceRoot }: Options = {}) {\n this.file = file;\n this.sourceRoot = sourceRoot;\n }\n\n static {\n addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name) => {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n\n const line = getLine(mappings, genLine);\n if (source == null) {\n const seg: SourceMapSegment = [genColumn];\n const index = getColumnIndex(line, genColumn, seg);\n return insert(line, index, seg);\n }\n\n // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source\n // isn't nullish.\n assert(sourceLine);\n assert(sourceColumn);\n const sourcesIndex = put(sources, source);\n const seg: SourceMapSegment = name\n ? [genColumn, sourcesIndex, sourceLine, sourceColumn, put(names, name)]\n : [genColumn, sourcesIndex, sourceLine, sourceColumn];\n\n const index = getColumnIndex(line, genColumn, seg);\n if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = null;\n insert(line, index, seg);\n };\n\n addMapping = (map, mapping) => {\n const { generated, source, original, name } = mapping;\n return (addSegment as any)(\n map,\n generated.line - 1,\n generated.column,\n source,\n original == null ? undefined : original.line - 1,\n original?.column,\n name,\n );\n };\n\n setSourceContent = (map, source, content) => {\n const { _sources: sources, _sourcesContent: sourcesContent } = map;\n sourcesContent[put(sources, source)] = content;\n };\n\n decodedMap = (map) => {\n const {\n file,\n sourceRoot,\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n\n return {\n version: 3,\n file,\n names: names.array,\n sourceRoot: sourceRoot || undefined,\n sources: sources.array,\n sourcesContent,\n mappings,\n };\n };\n\n encodedMap = (map) => {\n const decoded = decodedMap(map);\n return {\n ...decoded,\n mappings: encode(decoded.mappings as SourceMapSegment[][]),\n };\n };\n\n allMappings = (map) => {\n const out: Mapping[] = [];\n const { _mappings: mappings, _sources: sources, _names: names } = map;\n\n for (let i = 0; i < mappings.length; i++) {\n const line = mappings[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generated = { line: i + 1, column: seg[0] };\n let source: string | undefined = undefined;\n let original: Pos | undefined = undefined;\n let name: string | undefined = undefined;\n\n if (seg.length !== 1) {\n source = sources.array[seg[1]];\n original = { line: seg[2] + 1, column: seg[3] };\n\n if (seg.length === 5) name = names.array[seg[4]];\n }\n\n out.push({ generated, source, original, name } as Mapping);\n }\n }\n\n return out;\n };\n }\n}\n\nfunction assert(_val: unknown): asserts _val is T {\n // noop.\n}\n\nfunction getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] {\n for (let i = mappings.length; i <= index; i++) {\n mappings[i] = [];\n }\n return mappings[index];\n}\n\nfunction getColumnIndex(line: SourceMapSegment[], column: number, seg: SourceMapSegment): number {\n let index = line.length;\n for (let i = index - 1; i >= 0; i--, index--) {\n const current = line[i];\n const col = current[0];\n if (col > column) continue;\n if (col < column) break;\n\n const cmp = compare(current, seg);\n if (cmp === 0) return index;\n if (cmp < 0) break;\n }\n return index;\n}\n\nfunction compare(a: SourceMapSegment, b: SourceMapSegment): number {\n let cmp = compareNum(a.length, b.length);\n if (cmp !== 0) return cmp;\n\n // We've already checked genColumn\n if (a.length === 1) return 0;\n\n cmp = compareNum(a[1], b[1]!);\n if (cmp !== 0) return cmp;\n cmp = compareNum(a[2], b[2]!);\n if (cmp !== 0) return cmp;\n cmp = compareNum(a[3], b[3]!);\n if (cmp !== 0) return cmp;\n\n if (a.length === 4) return 0;\n return compareNum(a[4], b[4]!);\n}\n\nfunction compareNum(a: number, b: number): number {\n return a - b;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n if (index === -1) return;\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n"],"names":[],"mappings":";;;AAaA;;;AAGG;AACQ,IAAA,WA4BT;AAEF;;;AAGG;AACQ,IAAA,WA4BT;AAEF;;AAEG;AACQ,IAAA,iBAAoF;AAE/F;;;AAGG;AACQ,IAAA,WAAkD;AAE7D;;;AAGG;AACQ,IAAA,WAAkD;AAE7D;;;AAGG;AACQ,IAAA,YAA4C;AAEvD;;AAEG;MACU,UAAU,CAAA;AAQrB,IAAA,WAAA,CAAY,EAAE,I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;AAED,SAAS,UAAU,CAAC,CAAS,EAAE,CAAS,EAAA;IACtC,OAAO,CAAC,GAAG,CAAC,CAAC;AACf,CAAC;AAED,SAAS,MAAM,CAAI,KAAU,EAAE,KAAa,EAAE,KAAQ,EAAA;IACpD,IAAI,KAAK,KAAK,CAAC,CAAC;QAAE,OAAO;AACzB,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;QACzC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACzB,KAAA;AACD,IAAA,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;AACvB;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js new file mode 100644 index 0000000..46ecab7 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js @@ -0,0 +1,174 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/set-array'), require('@jridgewell/sourcemap-codec')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/set-array', '@jridgewell/sourcemap-codec'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.genMapping = {}, global.setArray, global.sourcemapCodec)); +})(this, (function (exports, setArray, sourcemapCodec) { 'use strict'; + + /** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ + exports.addSegment = void 0; + /** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ + exports.addMapping = void 0; + /** + * Adds/removes the content of the source file to the source map. + */ + exports.setSourceContent = void 0; + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.decodedMap = void 0; + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.encodedMap = void 0; + /** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ + exports.allMappings = void 0; + /** + * Provides the state to generate a sourcemap. + */ + class GenMapping { + constructor({ file, sourceRoot } = {}) { + this._names = new setArray.SetArray(); + this._sources = new setArray.SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + } + } + (() => { + exports.addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name) => { + const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + const line = getLine(mappings, genLine); + if (source == null) { + const seg = [genColumn]; + const index = getColumnIndex(line, genColumn, seg); + return insert(line, index, seg); + } + const sourcesIndex = setArray.put(sources, source); + const seg = name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, setArray.put(names, name)] + : [genColumn, sourcesIndex, sourceLine, sourceColumn]; + const index = getColumnIndex(line, genColumn, seg); + if (sourcesIndex === sourcesContent.length) + sourcesContent[sourcesIndex] = null; + insert(line, index, seg); + }; + exports.addMapping = (map, mapping) => { + const { generated, source, original, name } = mapping; + return exports.addSegment(map, generated.line - 1, generated.column, source, original == null ? undefined : original.line - 1, original === null || original === void 0 ? void 0 : original.column, name); + }; + exports.setSourceContent = (map, source, content) => { + const { _sources: sources, _sourcesContent: sourcesContent } = map; + sourcesContent[setArray.put(sources, source)] = content; + }; + exports.decodedMap = (map) => { + const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map; + return { + version: 3, + file, + names: names.array, + sourceRoot: sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + }; + }; + exports.encodedMap = (map) => { + const decoded = exports.decodedMap(map); + return Object.assign(Object.assign({}, decoded), { mappings: sourcemapCodec.encode(decoded.mappings) }); + }; + exports.allMappings = (map) => { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = map; + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[0] }; + let source = undefined; + let original = undefined; + let name = undefined; + if (seg.length !== 1) { + source = sources.array[seg[1]]; + original = { line: seg[2] + 1, column: seg[3] }; + if (seg.length === 5) + name = names.array[seg[4]]; + } + out.push({ generated, source, original, name }); + } + } + return out; + }; + })(); + function getLine(mappings, index) { + for (let i = mappings.length; i <= index; i++) { + mappings[i] = []; + } + return mappings[index]; + } + function getColumnIndex(line, column, seg) { + let index = line.length; + for (let i = index - 1; i >= 0; i--, index--) { + const current = line[i]; + const col = current[0]; + if (col > column) + continue; + if (col < column) + break; + const cmp = compare(current, seg); + if (cmp === 0) + return index; + if (cmp < 0) + break; + } + return index; + } + function compare(a, b) { + let cmp = compareNum(a.length, b.length); + if (cmp !== 0) + return cmp; + // We've already checked genColumn + if (a.length === 1) + return 0; + cmp = compareNum(a[1], b[1]); + if (cmp !== 0) + return cmp; + cmp = compareNum(a[2], b[2]); + if (cmp !== 0) + return cmp; + cmp = compareNum(a[3], b[3]); + if (cmp !== 0) + return cmp; + if (a.length === 4) + return 0; + return compareNum(a[4], b[4]); + } + function compareNum(a, b) { + return a - b; + } + function insert(array, index, value) { + if (index === -1) + return; + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + + exports.GenMapping = GenMapping; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=gen-mapping.umd.js.map diff --git a/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map new file mode 100644 index 0000000..1af9755 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.umd.js","sources":["../../src/gen-mapping.ts"],"sourcesContent":["import { SetArray, put } from '@jridgewell/set-array';\nimport { encode } from '@jridgewell/sourcemap-codec';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\nimport type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';\n\nexport type { DecodedSourceMap, EncodedSourceMap, Mapping };\n\nexport type Options = {\n file?: string | null;\n sourceRoot?: string | null;\n};\n\n/**\n * A low-level API to associate a generated position with an original source position. Line and\n * column here are 0-based, unlike `addMapping`.\n */\nexport let addSegment: {\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source?: null,\n sourceLine?: null,\n sourceColumn?: null,\n name?: null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name?: null,\n ): void;\n (\n map: GenMapping,\n genLine: number,\n genColumn: number,\n source: string,\n sourceLine: number,\n sourceColumn: number,\n name: string,\n ): void;\n};\n\n/**\n * A high-level API to associate a generated position with an original source position. Line is\n * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.\n */\nexport let addMapping: {\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source?: null;\n original?: null;\n name?: null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name?: null;\n },\n ): void;\n (\n map: GenMapping,\n mapping: {\n generated: Pos;\n source: string;\n original: Pos;\n name: string;\n },\n ): void;\n};\n\n/**\n * Adds/removes the content of the source file to the source map.\n */\nexport let setSourceContent: (map: GenMapping, source: string, content: string | null) => void;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let decodedMap: (map: GenMapping) => DecodedSourceMap;\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let encodedMap: (map: GenMapping) => EncodedSourceMap;\n\n/**\n * Returns an array of high-level mapping objects for every recorded segment, which could then be\n * passed to the `source-map` library.\n */\nexport let allMappings: (map: GenMapping) => Mapping[];\n\n/**\n * Provides the state to generate a sourcemap.\n */\nexport class GenMapping {\n private _names = new SetArray();\n private _sources = new SetArray();\n private _sourcesContent: (string | null)[] = [];\n private _mappings: SourceMapSegment[][] = [];\n declare file: string | null | undefined;\n declare sourceRoot: string | null | undefined;\n\n constructor({ file, sourceRoot }: Options = {}) {\n this.file = file;\n this.sourceRoot = sourceRoot;\n }\n\n static {\n addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name) => {\n const {\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n\n const line = getLine(mappings, genLine);\n if (source == null) {\n const seg: SourceMapSegment = [genColumn];\n const index = getColumnIndex(line, genColumn, seg);\n return insert(line, index, seg);\n }\n\n // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source\n // isn't nullish.\n assert(sourceLine);\n assert(sourceColumn);\n const sourcesIndex = put(sources, source);\n const seg: SourceMapSegment = name\n ? [genColumn, sourcesIndex, sourceLine, sourceColumn, put(names, name)]\n : [genColumn, sourcesIndex, sourceLine, sourceColumn];\n\n const index = getColumnIndex(line, genColumn, seg);\n if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = null;\n insert(line, index, seg);\n };\n\n addMapping = (map, mapping) => {\n const { generated, source, original, name } = mapping;\n return (addSegment as any)(\n map,\n generated.line - 1,\n generated.column,\n source,\n original == null ? undefined : original.line - 1,\n original?.column,\n name,\n );\n };\n\n setSourceContent = (map, source, content) => {\n const { _sources: sources, _sourcesContent: sourcesContent } = map;\n sourcesContent[put(sources, source)] = content;\n };\n\n decodedMap = (map) => {\n const {\n file,\n sourceRoot,\n _mappings: mappings,\n _sources: sources,\n _sourcesContent: sourcesContent,\n _names: names,\n } = map;\n\n return {\n version: 3,\n file,\n names: names.array,\n sourceRoot: sourceRoot || undefined,\n sources: sources.array,\n sourcesContent,\n mappings,\n };\n };\n\n encodedMap = (map) => {\n const decoded = decodedMap(map);\n return {\n ...decoded,\n mappings: encode(decoded.mappings as SourceMapSegment[][]),\n };\n };\n\n allMappings = (map) => {\n const out: Mapping[] = [];\n const { _mappings: mappings, _sources: sources, _names: names } = map;\n\n for (let i = 0; i < mappings.length; i++) {\n const line = mappings[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generated = { line: i + 1, column: seg[0] };\n let source: string | undefined = undefined;\n let original: Pos | undefined = undefined;\n let name: string | undefined = undefined;\n\n if (seg.length !== 1) {\n source = sources.array[seg[1]];\n original = { line: seg[2] + 1, column: seg[3] };\n\n if (seg.length === 5) name = names.array[seg[4]];\n }\n\n out.push({ generated, source, original, name } as Mapping);\n }\n }\n\n return out;\n };\n }\n}\n\nfunction assert(_val: unknown): asserts _val is T {\n // noop.\n}\n\nfunction getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] {\n for (let i = mappings.length; i <= index; i++) {\n mappings[i] = [];\n }\n return mappings[index];\n}\n\nfunction getColumnIndex(line: SourceMapSegment[], column: number, seg: SourceMapSegment): number {\n let index = line.length;\n for (let i = index - 1; i >= 0; i--, index--) {\n const current = line[i];\n const col = current[0];\n if (col > column) continue;\n if (col < column) break;\n\n const cmp = compare(current, seg);\n if (cmp === 0) return index;\n if (cmp < 0) break;\n }\n return index;\n}\n\nfunction compare(a: SourceMapSegment, b: SourceMapSegment): number {\n let cmp = compareNum(a.length, b.length);\n if (cmp !== 0) return cmp;\n\n // We've already checked genColumn\n if (a.length === 1) return 0;\n\n cmp = compareNum(a[1], b[1]!);\n if (cmp !== 0) return cmp;\n cmp = compareNum(a[2], b[2]!);\n if (cmp !== 0) return cmp;\n cmp = compareNum(a[3], b[3]!);\n if (cmp !== 0) return cmp;\n\n if (a.length === 4) return 0;\n return compareNum(a[4], b[4]!);\n}\n\nfunction compareNum(a: number, b: number): number {\n return a - b;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n if (index === -1) return;\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n"],"names":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C1B,IAAA,GAAG,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC;QAC9B,IAAI,GAAG,KAAK,CAAC;IAAE,QAAA,OAAO,GAAG,CAAC;IAE1B,IAAA,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC;IAAE,QAAA,OAAO,CAAC,CAAC;IAC7B,IAAA,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC;IACjC,CAAC;IAED,SAAS,UAAU,CAAC,CAAS,EAAE,CAAS,EAAA;QACtC,OAAO,CAAC,GAAG,CAAC,CAAC;IACf,CAAC;IAED,SAAS,MAAM,CAAI,KAAU,EAAE,KAAa,EAAE,KAAQ,EAAA;QACpD,IAAI,KAAK,KAAK,CAAC,CAAC;YAAE,OAAO;IACzB,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE;YACzC,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IACzB,KAAA;IACD,IAAA,KAAK,CAAC,KAAK,CAAC,GAAG,KAAK,CAAC;IACvB;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts new file mode 100644 index 0000000..22ca105 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts @@ -0,0 +1,70 @@ +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types'; +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; +export declare type Options = { + file?: string | null; + sourceRoot?: string | null; +}; +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export declare let addSegment: { + (map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null): void; + (map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null): void; + (map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string): void; +}; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export declare let addMapping: { + (map: GenMapping, mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + }): void; + (map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + }): void; + (map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + }): void; +}; +/** + * Adds/removes the content of the source file to the source map. + */ +export declare let setSourceContent: (map: GenMapping, source: string, content: string | null) => void; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let decodedMap: (map: GenMapping) => DecodedSourceMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let encodedMap: (map: GenMapping) => EncodedSourceMap; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export declare let allMappings: (map: GenMapping) => Mapping[]; +/** + * Provides the state to generate a sourcemap. + */ +export declare class GenMapping { + private _names; + private _sources; + private _sourcesContent; + private _mappings; + file: string | null | undefined; + sourceRoot: string | null | undefined; + constructor({ file, sourceRoot }?: Options); +} diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..e187ba9 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,12 @@ +declare type GeneratedColumn = number; +declare type SourcesIndex = number; +declare type SourceLine = number; +declare type SourceColumn = number; +declare type NamesIndex = number; +export declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export {}; diff --git a/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..b309c81 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts @@ -0,0 +1,35 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} +export interface Pos { + line: number; + column: number; +} +export declare type Mapping = { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; +} | { + generated: Pos; + source: string; + original: Pos; + name: string; +} | { + generated: Pos; + source: string; + original: Pos; + name: undefined; +}; diff --git a/node_modules/@jridgewell/gen-mapping/package.json b/node_modules/@jridgewell/gen-mapping/package.json new file mode 100644 index 0000000..e614b61 --- /dev/null +++ b/node_modules/@jridgewell/gen-mapping/package.json @@ -0,0 +1,72 @@ +{ + "name": "@jridgewell/gen-mapping", + "version": "0.1.1", + "description": "Generate source maps", + "keywords": [ + "source", + "map" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/gen-mapping", + "main": "dist/gen-mapping.umd.js", + "module": "dist/gen-mapping.mjs", + "typings": "dist/types/gen-mapping.d.ts", + "exports": { + ".": { + "browser": "./dist/gen-mapping.umd.js", + "require": "./dist/gen-mapping.umd.js", + "import": "./dist/gen-mapping.mjs" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node benchmark/index.mjs", + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:coverage", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "run-p 'build:rollup -- --watch' 'test:only -- --watch'", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.2", + "@types/mocha": "9.1.1", + "@types/node": "17.0.29", + "@typescript-eslint/eslint-plugin": "5.21.0", + "@typescript-eslint/parser": "5.21.0", + "benchmark": "2.1.4", + "c8": "7.11.2", + "eslint": "8.14.0", + "eslint-config-prettier": "8.5.0", + "mocha": "9.2.2", + "npm-run-all": "4.1.5", + "prettier": "2.6.2", + "rollup": "2.70.2", + "typescript": "4.6.3" + }, + "dependencies": { + "@jridgewell/set-array": "^1.0.0", + "@jridgewell/sourcemap-codec": "^1.4.10" + } +} diff --git a/node_modules/@jridgewell/resolve-uri/LICENSE b/node_modules/@jridgewell/resolve-uri/LICENSE new file mode 100644 index 0000000..0a81b2a --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/LICENSE @@ -0,0 +1,19 @@ +Copyright 2019 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/README.md b/node_modules/@jridgewell/resolve-uri/README.md new file mode 100644 index 0000000..2fe70df --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/README.md @@ -0,0 +1,40 @@ +# @jridgewell/resolve-uri + +> Resolve a URI relative to an optional base URI + +Resolve any combination of absolute URIs, protocol-realtive URIs, absolute paths, or relative paths. + +## Installation + +```sh +npm install @jridgewell/resolve-uri +``` + +## Usage + +```typescript +function resolve(input: string, base?: string): string; +``` + +```js +import resolve from '@jridgewell/resolve-uri'; + +resolve('foo', 'https://example.com'); // => 'https://example.com/foo' +``` + +| Input | Base | Resolution | Explanation | +|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------| +| `https://example.com` | _any_ | `https://example.com/` | Input is normalized only | +| `//example.com` | `https://base.com/` | `https://example.com/` | Input inherits the base's protocol | +| `//example.com` | _rest_ | `//example.com/` | Input is normalized only | +| `/example` | `https://base.com/` | `https://base.com/example` | Input inherits the base's origin | +| `/example` | `//base.com/` | `//base.com/example` | Input inherits the base's host and remains protocol relative | +| `/example` | _rest_ | `/example` | Input is normalized only | +| `example` | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base | +| `example` | `https://base.com/file` | `https://base.com/example` | Input is joined with the base without its file | +| `example` | `//base.com/dir/` | `//base.com/dir/example` | Input is joined with the base's last directory | +| `example` | `//base.com/file` | `//base.com/example` | Input is joined with the base without its file | +| `example` | `/base/dir/` | `/base/dir/example` | Input is joined with the base's last directory | +| `example` | `/base/file` | `/base/example` | Input is joined with the base without its file | +| `example` | `base/dir/` | `base/dir/example` | Input is joined with the base's last directory | +| `example` | `base/file` | `base/example` | Input is joined with the base without its file | diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs new file mode 100644 index 0000000..94d8dce --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs @@ -0,0 +1,242 @@ +// Matches the scheme of a URL, eg "http://" +const schemeRegex = /^[\w+.-]+:\/\//; +/** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ +const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +/** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ +const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +var UrlType; +(function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; +})(UrlType || (UrlType = {})); +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith('//'); +} +function isAbsolutePath(input) { + return input.startsWith('/'); +} +function isFileUrl(input) { + return input.startsWith('file:'); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); +} +function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: UrlType.Absolute, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.AbsolutePath; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.Empty; + return url; +} +function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } +} +/** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ +function normalizePath(url, type) { + const rel = type <= UrlType.RelativePath; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; +} +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.AbsolutePath: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case UrlType.SchemeRelative: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.RelativePath: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // 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. + return './' + path + queryHash; + } + return path + queryHash; + } + case UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +export { resolve as default }; +//# sourceMappingURL=resolve-uri.mjs.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map new file mode 100644 index 0000000..009d043 --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.mjs","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nenum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":"AAAA;AACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC;;;;;;;;;;AAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;AAE5F;;;;;;;;;AASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;AAapF,IAAK,OAQJ;AARD,WAAK,OAAO;IACV,uCAAS,CAAA;IACT,qCAAQ,CAAA;IACR,uCAAS,CAAA;IACT,qDAAgB,CAAA;IAChB,qDAAgB,CAAA;IAChB,yDAAkB,CAAA;IAClB,6CAAY,CAAA;AACd,CAAC,EARI,OAAO,KAAP,OAAO,QAQX;AAED,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC9B,OAAO,KAAK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G,CAAC,IAAI,GAAG,SAAS,CAAC;KACpF;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js new file mode 100644 index 0000000..0700a2d --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js @@ -0,0 +1,250 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory()); +})(this, (function () { 'use strict'; + + // Matches the scheme of a URL, eg "http://" + const schemeRegex = /^[\w+.-]+:\/\//; + /** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ + const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; + /** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ + const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; + var UrlType; + (function (UrlType) { + UrlType[UrlType["Empty"] = 1] = "Empty"; + UrlType[UrlType["Hash"] = 2] = "Hash"; + UrlType[UrlType["Query"] = 3] = "Query"; + UrlType[UrlType["RelativePath"] = 4] = "RelativePath"; + UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath"; + UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative"; + UrlType[UrlType["Absolute"] = 7] = "Absolute"; + })(UrlType || (UrlType = {})); + function isAbsoluteUrl(input) { + return schemeRegex.test(input); + } + function isSchemeRelativeUrl(input) { + return input.startsWith('//'); + } + function isAbsolutePath(input) { + return input.startsWith('/'); + } + function isFileUrl(input) { + return input.startsWith('file:'); + } + function isRelative(input) { + return /^[.?#]/.test(input); + } + function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); + } + function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); + } + function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: UrlType.Absolute, + }; + } + function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = UrlType.SchemeRelative; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = UrlType.AbsolutePath; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? UrlType.Query + : input.startsWith('#') + ? UrlType.Hash + : UrlType.RelativePath + : UrlType.Empty; + return url; + } + function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } + } + /** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ + function normalizePath(url, type) { + const rel = type <= UrlType.RelativePath; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; + } + /** + * Attempts to resolve `input` URL/path relative to `base`. + */ + function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== UrlType.Absolute) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case UrlType.Empty: + url.hash = baseUrl.hash; + // fall through + case UrlType.Hash: + url.query = baseUrl.query; + // fall through + case UrlType.Query: + case UrlType.RelativePath: + mergePaths(url, baseUrl); + // fall through + case UrlType.AbsolutePath: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case UrlType.SchemeRelative: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case UrlType.Hash: + case UrlType.Query: + return queryHash; + case UrlType.RelativePath: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // 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. + return './' + path + queryHash; + } + return path + queryHash; + } + case UrlType.AbsolutePath: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } + } + + return resolve; + +})); +//# sourceMappingURL=resolve-uri.umd.js.map diff --git a/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map new file mode 100644 index 0000000..a3e39eb --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.umd.js","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex = /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?([^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nenum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":";;;;;;IAAA;IACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;IAErC;;;;;;;;;;IAUA,MAAM,QAAQ,GAAG,0EAA0E,CAAC;IAE5F;;;;;;;;;IASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;IAapF,IAAK,OAQJ;IARD,WAAK,OAAO;QACV,uCAAS,CAAA;QACT,qCAAQ,CAAA;QACR,uCAAS,CAAA;QACT,qDAAgB,CAAA;QAChB,qDAAgB,CAAA;QAChB,yDAAkB,CAAA;QAClB,6CAAY,CAAA;IACd,CAAC,EARI,OAAO,KAAP,OAAO,QAQX;IAED,SAAS,aAAa,CAAC,KAAa;QAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,SAAS,mBAAmB,CAAC,KAAa;QACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;IAED,SAAS,cAAc,CAAC,KAAa;QACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,SAAS,SAAS,CAAC,KAAa;QAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACnC,CAAC;IAED,SAAS,U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SACpF;IACH;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts new file mode 100644 index 0000000..b7f0b3b --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts @@ -0,0 +1,4 @@ +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/resolve-uri/package.json b/node_modules/@jridgewell/resolve-uri/package.json new file mode 100644 index 0000000..114937a --- /dev/null +++ b/node_modules/@jridgewell/resolve-uri/package.json @@ -0,0 +1,69 @@ +{ + "name": "@jridgewell/resolve-uri", + "version": "3.1.0", + "description": "Resolve a URI relative to an optional base URI", + "keywords": [ + "resolve", + "uri", + "url", + "path" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/resolve-uri", + "main": "dist/resolve-uri.umd.js", + "module": "dist/resolve-uri.mjs", + "typings": "dist/types/resolve-uri.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/resolve-uri.d.ts", + "browser": "./dist/resolve-uri.umd.js", + "require": "./dist/resolve-uri.umd.js", + "import": "./dist/resolve-uri.mjs" + }, + "./dist/resolve-uri.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@jridgewell/resolve-uri-latest": "npm:@jridgewell/resolve-uri@*", + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "typescript": "4.5.5" + } +} diff --git a/node_modules/@jridgewell/set-array/LICENSE b/node_modules/@jridgewell/set-array/LICENSE new file mode 100644 index 0000000..352f071 --- /dev/null +++ b/node_modules/@jridgewell/set-array/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jridgewell/set-array/README.md b/node_modules/@jridgewell/set-array/README.md new file mode 100644 index 0000000..2ed155f --- /dev/null +++ b/node_modules/@jridgewell/set-array/README.md @@ -0,0 +1,37 @@ +# @jridgewell/set-array + +> Like a Set, 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 in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, and there +are never duplicates. + +## Installation + +```sh +npm install @jridgewell/set-array +``` + +## Usage + +```js +import { SetArray, get, put, pop } from '@jridgewell/set-array'; + +const sa = new SetArray(); + +let index = put(sa, 'first'); +assert.strictEqual(index, 0); + +index = put(sa, 'second'); +assert.strictEqual(index, 1); + +assert.deepEqual(sa.array, [ 'first', 'second' ]); + +index = get(sa, 'first'); +assert.strictEqual(index, 0); + +pop(sa); +index = get(sa, 'second'); +assert.strictEqual(index, undefined); +assert.deepEqual(sa.array, [ 'first' ]); +``` diff --git a/node_modules/@jridgewell/set-array/dist/set-array.mjs b/node_modules/@jridgewell/set-array/dist/set-array.mjs new file mode 100644 index 0000000..b7f1a9c --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.mjs @@ -0,0 +1,48 @@ +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +let get; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +let put; +/** + * Pops the last added item out of the SetArray. + */ +let pop; +/** + * SetArray 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 in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +class SetArray { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } +} +(() => { + get = (strarr, key) => strarr._indexes[key]; + put = (strarr, key) => { + // The key may or may not be present. If it is present, it's a number. + const index = get(strarr, key); + if (index !== undefined) + return index; + const { array, _indexes: indexes } = strarr; + return (indexes[key] = array.push(key) - 1); + }; + pop = (strarr) => { + const { array, _indexes: indexes } = strarr; + if (array.length === 0) + return; + const last = array.pop(); + indexes[last] = undefined; + }; +})(); + +export { SetArray, get, pop, put }; +//# sourceMappingURL=set-array.mjs.map diff --git a/node_modules/@jridgewell/set-array/dist/set-array.mjs.map b/node_modules/@jridgewell/set-array/dist/set-array.mjs.map new file mode 100644 index 0000000..ead5643 --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.mjs","sources":["../src/set-array.ts"],"sourcesContent":["/**\n * Gets the index associated with `key` in the backing array, if it is already present.\n */\nexport let get: (strarr: SetArray, key: string) => number | undefined;\n\n/**\n * Puts `key` into the backing array, if it is not already present. Returns\n * the index of the `key` in the backing array.\n */\nexport let put: (strarr: SetArray, key: string) => number;\n\n/**\n * Pops the last added item out of the SetArray.\n */\nexport let pop: (strarr: SetArray) => void;\n\n/**\n * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the\n * index of the `key` in the backing array.\n *\n * This is designed to allow synchronizing a second array with the contents of the backing array,\n * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,\n * and there are never duplicates.\n */\nexport class SetArray {\n private declare _indexes: { [key: string]: number | undefined };\n declare array: readonly string[];\n\n constructor() {\n this._indexes = { __proto__: null } as any;\n this.array = [];\n }\n\n static {\n get = (strarr, key) => strarr._indexes[key];\n\n put = (strarr, key) => {\n // The key may or may not be present. If it is present, it's a number.\n const index = get(strarr, key);\n if (index !== undefined) return index;\n\n const { array, _indexes: indexes } = strarr;\n\n return (indexes[key] = (array as string[]).push(key) - 1);\n };\n\n pop = (strarr) => {\n const { array, _indexes: indexes } = strarr;\n if (array.length === 0) return;\n\n const last = (array as string[]).pop()!;\n indexes[last] = undefined;\n };\n }\n}\n"],"names":[],"mappings":"AAAA;;;IAGW,IAA2D;AAEtE;;;;IAIW,IAA+C;AAE1D;;;IAGW,IAAgC;AAE3C;;;;;;;;MAQa,QAAQ;IAInB;QACE,IAAI,CAAC,QAAQ,GAAG,EAAE,SAAS,EAAE,IAAI,EAAS,CAAC;QAC3C,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;KACjB;CAuBF;AArBC;IACE,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,KAAK,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAE5C,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG;;QAEhB,MAAM,KAAK,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC/B,IAAI,KAAK,KAAK,SAAS;YAAE,OAAO,KAAK,CAAC;QAEtC,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;QAE5C,QAAQ,OAAO,CAAC,GAAG,CAAC,GAAI,KAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;KAC3D,CAAC;IAEF,GAAG,GAAG,CAAC,MAAM;QACX,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;QAC5C,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO;QAE/B,MAAM,IAAI,GAAI,KAAkB,CAAC,GAAG,EAAG,CAAC;QACxC,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC;KAC3B,CAAC;AACJ,CAAC,GAAA;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/set-array/dist/set-array.umd.js b/node_modules/@jridgewell/set-array/dist/set-array.umd.js new file mode 100644 index 0000000..a1c200a --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.umd.js @@ -0,0 +1,58 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.setArray = {})); +})(this, (function (exports) { 'use strict'; + + /** + * Gets the index associated with `key` in the backing array, if it is already present. + */ + exports.get = void 0; + /** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ + exports.put = void 0; + /** + * Pops the last added item out of the SetArray. + */ + exports.pop = void 0; + /** + * SetArray 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 in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ + class SetArray { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } + } + (() => { + exports.get = (strarr, key) => strarr._indexes[key]; + exports.put = (strarr, key) => { + // The key may or may not be present. If it is present, it's a number. + const index = exports.get(strarr, key); + if (index !== undefined) + return index; + const { array, _indexes: indexes } = strarr; + return (indexes[key] = array.push(key) - 1); + }; + exports.pop = (strarr) => { + const { array, _indexes: indexes } = strarr; + if (array.length === 0) + return; + const last = array.pop(); + indexes[last] = undefined; + }; + })(); + + exports.SetArray = SetArray; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=set-array.umd.js.map diff --git a/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map b/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map new file mode 100644 index 0000000..10005af --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/set-array.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.umd.js","sources":["../src/set-array.ts"],"sourcesContent":["/**\n * Gets the index associated with `key` in the backing array, if it is already present.\n */\nexport let get: (strarr: SetArray, key: string) => number | undefined;\n\n/**\n * Puts `key` into the backing array, if it is not already present. Returns\n * the index of the `key` in the backing array.\n */\nexport let put: (strarr: SetArray, key: string) => number;\n\n/**\n * Pops the last added item out of the SetArray.\n */\nexport let pop: (strarr: SetArray) => void;\n\n/**\n * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the\n * index of the `key` in the backing array.\n *\n * This is designed to allow synchronizing a second array with the contents of the backing array,\n * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,\n * and there are never duplicates.\n */\nexport class SetArray {\n private declare _indexes: { [key: string]: number | undefined };\n declare array: readonly string[];\n\n constructor() {\n this._indexes = { __proto__: null } as any;\n this.array = [];\n }\n\n static {\n get = (strarr, key) => strarr._indexes[key];\n\n put = (strarr, key) => {\n // The key may or may not be present. If it is present, it's a number.\n const index = get(strarr, key);\n if (index !== undefined) return index;\n\n const { array, _indexes: indexes } = strarr;\n\n return (indexes[key] = (array as string[]).push(key) - 1);\n };\n\n pop = (strarr) => {\n const { array, _indexes: indexes } = strarr;\n if (array.length === 0) return;\n\n const last = (array as string[]).pop()!;\n indexes[last] = undefined;\n };\n }\n}\n"],"names":["get","put","pop"],"mappings":";;;;;;IAAA;;;AAGWA,yBAA2D;IAEtE;;;;AAIWC,yBAA+C;IAE1D;;;AAGWC,yBAAgC;IAE3C;;;;;;;;UAQa,QAAQ;QAInB;YACE,IAAI,CAAC,QAAQ,GAAG,EAAE,SAAS,EAAE,IAAI,EAAS,CAAC;YAC3C,IAAI,CAAC,KAAK,GAAG,EAAE,CAAC;SACjB;KAuBF;IArBC;QACEF,WAAG,GAAG,CAAC,MAAM,EAAE,GAAG,KAAK,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QAE5CC,WAAG,GAAG,CAAC,MAAM,EAAE,GAAG;;YAEhB,MAAM,KAAK,GAAGD,WAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;YAC/B,IAAI,KAAK,KAAK,SAAS;gBAAE,OAAO,KAAK,CAAC;YAEtC,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;YAE5C,QAAQ,OAAO,CAAC,GAAG,CAAC,GAAI,KAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE;SAC3D,CAAC;QAEFE,WAAG,GAAG,CAAC,MAAM;YACX,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC;YAC5C,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO;YAE/B,MAAM,IAAI,GAAI,KAAkB,CAAC,GAAG,EAAG,CAAC;YACxC,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC;SAC3B,CAAC;IACJ,CAAC,GAAA;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts b/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts new file mode 100644 index 0000000..7ed59b9 --- /dev/null +++ b/node_modules/@jridgewell/set-array/dist/types/set-array.d.ts @@ -0,0 +1,26 @@ +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export declare let get: (strarr: SetArray, key: string) => number | undefined; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export declare let put: (strarr: SetArray, key: string) => number; +/** + * Pops the last added item out of the SetArray. + */ +export declare let pop: (strarr: SetArray) => void; +/** + * SetArray 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 in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export declare class SetArray { + private _indexes; + array: readonly string[]; + constructor(); +} diff --git a/node_modules/@jridgewell/set-array/package.json b/node_modules/@jridgewell/set-array/package.json new file mode 100644 index 0000000..aec4ee0 --- /dev/null +++ b/node_modules/@jridgewell/set-array/package.json @@ -0,0 +1,66 @@ +{ + "name": "@jridgewell/set-array", + "version": "1.1.2", + "description": "Like a Set, but provides the index of the `key` in the backing array", + "keywords": [], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/set-array", + "main": "dist/set-array.umd.js", + "module": "dist/set-array.mjs", + "typings": "dist/types/set-array.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/set-array.d.ts", + "browser": "./dist/set-array.umd.js", + "require": "./dist/set-array.umd.js", + "import": "./dist/set-array.mjs" + }, + "./dist/set-array.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist", + "src" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@types/mocha": "9.1.1", + "@types/node": "17.0.29", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "typescript": "4.5.5" + } +} diff --git a/node_modules/@jridgewell/set-array/src/set-array.ts b/node_modules/@jridgewell/set-array/src/set-array.ts new file mode 100644 index 0000000..f9ff604 --- /dev/null +++ b/node_modules/@jridgewell/set-array/src/set-array.ts @@ -0,0 +1,55 @@ +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export let get: (strarr: SetArray, key: string) => number | undefined; + +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export let put: (strarr: SetArray, key: string) => number; + +/** + * Pops the last added item out of the SetArray. + */ +export let pop: (strarr: SetArray) => void; + +/** + * SetArray 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 in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export class SetArray { + private declare _indexes: { [key: string]: number | undefined }; + declare array: readonly string[]; + + constructor() { + this._indexes = { __proto__: null } as any; + this.array = []; + } + + static { + get = (strarr, key) => strarr._indexes[key]; + + put = (strarr, key) => { + // The key may or may not be present. If it is present, it's a number. + const index = get(strarr, key); + if (index !== undefined) return index; + + const { array, _indexes: indexes } = strarr; + + return (indexes[key] = (array as string[]).push(key) - 1); + }; + + pop = (strarr) => { + const { array, _indexes: indexes } = strarr; + if (array.length === 0) return; + + const last = (array as string[]).pop()!; + indexes[last] = undefined; + }; + } +} diff --git a/node_modules/@jridgewell/sourcemap-codec/LICENSE b/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 0000000..a331065 --- /dev/null +++ b/node_modules/@jridgewell/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/@jridgewell/sourcemap-codec/README.md b/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 0000000..2b9e397 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,200 @@ +# 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' ); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 5479160 bytes +sourcemap-codec 5659336 bytes +source-map-0.6.1 17144440 bytes +source-map-0.8.0 6867424 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 502 ops/sec ±1.03% (90 runs sampled) +decode: sourcemap-codec x 445 ops/sec ±0.97% (92 runs sampled) +decode: source-map-0.6.1 x 36.01 ops/sec ±1.64% (49 runs sampled) +decode: source-map-0.8.0 x 367 ops/sec ±0.04% (95 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 1261620 bytes +sourcemap-codec 9119248 bytes +source-map-0.6.1 8968560 bytes +source-map-0.8.0 8952952 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 738 ops/sec ±0.42% (98 runs sampled) +encode: sourcemap-codec x 238 ops/sec ±0.73% (88 runs sampled) +encode: source-map-0.6.1 x 162 ops/sec ±0.43% (84 runs sampled) +encode: source-map-0.8.0 x 191 ops/sec ±0.34% (90 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 35338184 bytes +sourcemap-codec 35922736 bytes +source-map-0.6.1 62366360 bytes +source-map-0.8.0 44337416 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 40.35 ops/sec ±4.47% (54 runs sampled) +decode: sourcemap-codec x 36.76 ops/sec ±3.67% (51 runs sampled) +decode: source-map-0.6.1 x 4.44 ops/sec ±2.15% (16 runs sampled) +decode: source-map-0.8.0 x 59.35 ops/sec ±0.05% (78 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +@jridgewell/sourcemap-codec 7212604 bytes +sourcemap-codec 21421456 bytes +source-map-0.6.1 25286888 bytes +source-map-0.8.0 25498744 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 112 ops/sec ±0.13% (84 runs sampled) +encode: sourcemap-codec x 30.23 ops/sec ±2.76% (53 runs sampled) +encode: source-map-0.6.1 x 19.43 ops/sec ±3.70% (37 runs sampled) +encode: source-map-0.8.0 x 19.40 ops/sec ±3.26% (37 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 500272 bytes +sourcemap-codec 516864 bytes +source-map-0.6.1 1596672 bytes +source-map-0.8.0 517272 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 16,137 ops/sec ±0.17% (99 runs sampled) +decode: sourcemap-codec x 12,139 ops/sec ±0.13% (99 runs sampled) +decode: source-map-0.6.1 x 1,264 ops/sec ±0.12% (100 runs sampled) +decode: source-map-0.8.0 x 9,894 ops/sec ±0.08% (101 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 321026 bytes +sourcemap-codec 830832 bytes +source-map-0.6.1 586608 bytes +source-map-0.8.0 586680 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 19,876 ops/sec ±0.78% (95 runs sampled) +encode: sourcemap-codec x 6,983 ops/sec ±0.15% (100 runs sampled) +encode: source-map-0.6.1 x 5,070 ops/sec ±0.12% (102 runs sampled) +encode: source-map-0.8.0 x 5,641 ops/sec ±0.17% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +@jridgewell/sourcemap-codec 734848 bytes +sourcemap-codec 954200 bytes +source-map-0.6.1 2276432 bytes +source-map-0.8.0 955488 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Decode speed: +decode: @jridgewell/sourcemap-codec x 5,723 ops/sec ±0.12% (98 runs sampled) +decode: sourcemap-codec x 4,555 ops/sec ±0.09% (101 runs sampled) +decode: source-map-0.6.1 x 437 ops/sec ±0.11% (93 runs sampled) +decode: source-map-0.8.0 x 3,441 ops/sec ±0.15% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec + +Encode Memory Usage: +@jridgewell/sourcemap-codec 638672 bytes +sourcemap-codec 1109840 bytes +source-map-0.6.1 1321224 bytes +source-map-0.8.0 1324448 bytes +Smallest memory usage is @jridgewell/sourcemap-codec + +Encode speed: +encode: @jridgewell/sourcemap-codec x 6,801 ops/sec ±0.48% (98 runs sampled) +encode: sourcemap-codec x 2,533 ops/sec ±0.13% (101 runs sampled) +encode: source-map-0.6.1 x 2,248 ops/sec ±0.08% (100 runs sampled) +encode: source-map-0.8.0 x 2,303 ops/sec ±0.15% (100 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec +``` + +# License + +MIT diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 0000000..3dff372 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,164 @@ +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +// Provide a fallback for older environments. +const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; +function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; +} +function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} +function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; +} +function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); +} +function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; +} + +export { decode, encode }; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 0000000..36d7249 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.mjs","sources":["../src/sourcemap-codec.ts"],"sourcesContent":[null],"names":[],"mappings":"AAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;AACjF,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACrC,MAAM,SAAS,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AAEtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;IACrC,MAAM,CAAC,GAAG,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9B,SAAS,CAAC,CAAC,CAAC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GAAG,IAAI,CAAC;IAEhB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;IAC3C,GAAG;QACD,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;QAC7B,GAAG,MAAM,CAAC,CAAC;QACX,IAAI,GAAG,GAAG,CAAC;YAAE,OAAO,IAAI,QAAQ,CAAC;QACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;KACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;IAElB,OAAO,GAAG,CAAC;AACb;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000..bec92a9 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,175 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sourcemapCodec = {})); +})(this, (function (exports) { 'use strict'; + + const comma = ','.charCodeAt(0); + const semicolon = ';'.charCodeAt(0); + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + const intToChar = new Uint8Array(64); // 64 possible chars. + const charToInt = new Uint8Array(128); // z is 122 in ASCII + for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; + } + // Provide a fallback for older environments. + const td = typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + function decode(mappings) { + const state = new Int32Array(5); + const decoded = []; + let index = 0; + do { + const semi = indexOf(mappings, index); + const line = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + for (let i = index; i < semi; i++) { + let seg; + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) + sorted = false; + lastCol = col; + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } + else { + seg = [col, state[1], state[2], state[3]]; + } + } + else { + seg = [col]; + } + line.push(seg); + } + if (!sorted) + sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + return decoded; + } + function indexOf(mappings, index) { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; + } + function decodeInteger(mappings, pos, state, j) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + const shouldNegate = value & 1; + value >>>= 1; + if (shouldNegate) { + value = -0x80000000 | -value; + } + state[j] += value; + return pos; + } + function hasMoreVlq(mappings, i, length) { + if (i >= length) + return false; + return mappings.charCodeAt(i) !== comma; + } + function sort(line) { + line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[0] - b[0]; + } + function encode(decoded) { + const state = new Int32Array(5); + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) + continue; + state[0] = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) + buf[pos++] = comma; + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + if (segment.length === 1) + continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + if (segment.length === 4) + continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + return out + td.decode(buf.subarray(0, pos)); + } + function encodeInteger(buf, pos, state, segment, j) { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) + clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + return pos; + } + + exports.decode = decode; + exports.encode = encode; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000..a7a4628 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.umd.js","sources":["../src/sourcemap-codec.ts"],"sourcesContent":[null],"names":[],"mappings":";;;;;;IAOA,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAChC,MAAM,SAAS,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACpC,MAAM,KAAK,GAAG,kEAAkE,CAAC;IACjF,MA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O,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;IAC/C,CAAC;IAED,SAAS,aAAa,CACpB,GAAe,EACf,GAAW,EACX,KAAuB,EACvB,OAAyB,EACzB,CAAS;QAET,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QACxB,IAAI,GAAG,GAAG,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QAC1B,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;QAEhB,GAAG,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,CAAC;QAC3C,GAAG;YACD,IAAI,OAAO,GAAG,GAAG,GAAG,QAAQ,CAAC;YAC7B,GAAG,MAAM,CAAC,CAAC;YACX,IAAI,GAAG,GAAG,CAAC;gBAAE,OAAO,IAAI,QAAQ,CAAC;YACjC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,SAAS,CAAC,OAAO,CAAC,CAAC;SACjC,QAAQ,GAAG,GAAG,CAAC,EAAE;QAElB,OAAO,GAAG,CAAC;IACb;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts new file mode 100644 index 0000000..410d320 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/dist/types/sourcemap-codec.d.ts @@ -0,0 +1,6 @@ +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; +export declare function encode(decoded: Readonly): string; diff --git a/node_modules/@jridgewell/sourcemap-codec/package.json b/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 0000000..5945072 --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,75 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.4.14", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "typings": "dist/types/sourcemap-codec.d.ts", + "files": [ + "dist", + "src" + ], + "exports": { + ".": [ + { + "types": "./dist/types/sourcemap-codec.d.ts", + "browser": "./dist/sourcemap-codec.umd.js", + "import": "./dist/sourcemap-codec.mjs", + "require": "./dist/sourcemap-codec.umd.js" + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemap-codec.git" + }, + "author": "Rich Harris", + "license": "MIT", + "devDependencies": { + "@rollup/plugin-typescript": "8.3.0", + "@types/node": "17.0.15", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "benchmark": "2.1.4", + "c8": "7.11.2", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.64.0", + "source-map": "0.6.1", + "source-map-js": "1.0.2", + "sourcemap-codec": "1.4.8", + "typescript": "4.5.4" + } +} diff --git a/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts b/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts new file mode 100644 index 0000000..cafd90e --- /dev/null +++ b/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts @@ -0,0 +1,198 @@ +export type SourceMapSegment = + | [number] + | [number, number, number, number] + | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; + +const comma = ','.charCodeAt(0); +const semicolon = ';'.charCodeAt(0); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII + +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} + +// Provide a fallback for older environments. +const td = + typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf: Uint8Array) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf: Uint8Array) { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + +export function decode(mappings: string): SourceMapMappings { + const state: [number, number, number, number, number] = new Int32Array(5) as any; + const decoded: SourceMapMappings = []; + + let index = 0; + do { + const semi = indexOf(mappings, index); + const line: SourceMapLine = []; + let sorted = true; + let lastCol = 0; + state[0] = 0; + + for (let i = index; i < semi; i++) { + let seg: SourceMapSegment; + + i = decodeInteger(mappings, i, state, 0); // genColumn + const col = state[0]; + if (col < lastCol) sorted = false; + lastCol = col; + + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 1); // sourcesIndex + i = decodeInteger(mappings, i, state, 2); // sourceLine + i = decodeInteger(mappings, i, state, 3); // sourceColumn + + if (hasMoreVlq(mappings, i, semi)) { + i = decodeInteger(mappings, i, state, 4); // namesIndex + seg = [col, state[1], state[2], state[3], state[4]]; + } else { + seg = [col, state[1], state[2], state[3]]; + } + } else { + seg = [col]; + } + + line.push(seg); + } + + if (!sorted) sort(line); + decoded.push(line); + index = semi + 1; + } while (index <= mappings.length); + + return decoded; +} + +function indexOf(mappings: string, index: number): number { + const idx = mappings.indexOf(';', index); + return idx === -1 ? mappings.length : idx; +} + +function decodeInteger(mappings: string, pos: number, state: SourceMapSegment, j: number): number { + let value = 0; + let shift = 0; + let integer = 0; + + do { + const c = mappings.charCodeAt(pos++); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + + const shouldNegate = value & 1; + value >>>= 1; + + if (shouldNegate) { + value = -0x80000000 | -value; + } + + state[j] += value; + return pos; +} + +function hasMoreVlq(mappings: string, i: number, length: number): boolean { + if (i >= length) return false; + return mappings.charCodeAt(i) !== comma; +} + +function sort(line: SourceMapSegment[]) { + line.sort(sortComparator); +} + +function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number { + return a[0] - b[0]; +} + +export function encode(decoded: SourceMapMappings): string; +export function encode(decoded: Readonly): string; +export function encode(decoded: Readonly): string { + const state: [number, number, number, number, number] = new Int32Array(5) as any; + const bufLength = 1024 * 16; + const subLength = bufLength - 36; + const buf = new Uint8Array(bufLength); + const sub = buf.subarray(0, subLength); + let pos = 0; + let out = ''; + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) { + if (pos === bufLength) { + out += td.decode(buf); + pos = 0; + } + buf[pos++] = semicolon; + } + if (line.length === 0) continue; + + state[0] = 0; + + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + // We can push up to 5 ints, each int can take at most 7 chars, and we + // may push a comma. + if (pos > subLength) { + out += td.decode(sub); + buf.copyWithin(0, subLength, pos); + pos -= subLength; + } + if (j > 0) buf[pos++] = comma; + + pos = encodeInteger(buf, pos, state, segment, 0); // genColumn + + if (segment.length === 1) continue; + pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex + pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine + pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn + + if (segment.length === 4) continue; + pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex + } + } + + return out + td.decode(buf.subarray(0, pos)); +} + +function encodeInteger( + buf: Uint8Array, + pos: number, + state: SourceMapSegment, + segment: SourceMapSegment, + j: number, +): number { + const next = segment[j]; + let num = next - state[j]; + state[j] = next; + + num = num < 0 ? (-num << 1) | 1 : num << 1; + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) clamped |= 0b100000; + buf[pos++] = intToChar[clamped]; + } while (num > 0); + + return pos; +} diff --git a/node_modules/@jridgewell/trace-mapping/LICENSE b/node_modules/@jridgewell/trace-mapping/LICENSE new file mode 100644 index 0000000..37bb488 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2022 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/@jridgewell/trace-mapping/README.md b/node_modules/@jridgewell/trace-mapping/README.md new file mode 100644 index 0000000..cc5e4f9 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/README.md @@ -0,0 +1,252 @@ +# @jridgewell/trace-mapping + +> Trace the original position through a source map + +`trace-mapping` allows you to take the line and column of an output file and trace it to the +original location in the source file through a source map. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapConsumer`. This +provides the same `originalPositionFor` and `generatedPositionFor` API, without requiring WASM. + +## Installation + +```sh +npm install @jridgewell/trace-mapping +``` + +## Usage + +```typescript +import { + TraceMap, + originalPositionFor, + generatedPositionFor, + sourceContentFor, +} from '@jridgewell/trace-mapping'; + +const tracer = new TraceMap({ + version: 3, + sources: ['input.js'], + sourcesContent: ['content of input.js'], + names: ['foo'], + mappings: 'KAyCIA', +}); + +// Lines start at line 1, columns at column 0. +const traced = originalPositionFor(tracer, { line: 1, column: 5 }); +assert.deepEqual(traced, { + source: 'input.js', + line: 42, + column: 4, + name: 'foo', +}); + +const content = sourceContentFor(tracer, traced.source); +assert.strictEqual(content, 'content for input.js'); + +const generated = generatedPositionFor(tracer, { + source: 'input.js', + line: 42, + column: 4, +}); +assert.deepEqual(generated, { + line: 1, + column: 5, +}); +``` + +We also provide a lower level API to get the actual segment that matches our line and column. Unlike +`originalPositionFor`, `traceSegment` uses a 0-base for `line`: + +```typescript +import { traceSegment } from '@jridgewell/trace-mapping'; + +// line is 0-base. +const traced = traceSegment(tracer, /* line */ 0, /* column */ 5); + +// Segments are [outputColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] +// Again, line is 0-base and so is sourceLine +assert.deepEqual(traced, [5, 0, 41, 4, 0]); +``` + +### SectionedSourceMaps + +The sourcemap spec defines a special `sections` field that's designed to handle concatenation of +output code with associated sourcemaps. This type of sourcemap is rarely used (no major build tool +produces it), but if you are hand coding a concatenation you may need it. We provide an `AnyMap` +helper that can receive either a regular sourcemap or a `SectionedSourceMap` and returns a +`TraceMap` instance: + +```typescript +import { AnyMap } from '@jridgewell/trace-mapping'; +const fooOutput = 'foo'; +const barOutput = 'bar'; +const output = [fooOutput, barOutput].join('\n'); + +const sectioned = new AnyMap({ + version: 3, + sections: [ + { + // 0-base line and column + offset: { line: 0, column: 0 }, + // fooOutput's sourcemap + map: { + version: 3, + sources: ['foo.js'], + names: ['foo'], + mappings: 'AAAAA', + }, + }, + { + // barOutput's sourcemap will not affect the first line, only the second + offset: { line: 1, column: 0 }, + map: { + version: 3, + sources: ['bar.js'], + names: ['bar'], + mappings: 'AAAAA', + }, + }, + ], +}); + +const traced = originalPositionFor(sectioned, { + line: 2, + column: 0, +}); + +assert.deepEqual(traced, { + source: 'bar.js', + line: 1, + column: 0, + name: 'bar', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map - 45120 segments + +Memory Usage: +trace-mapping decoded 562400 bytes +trace-mapping encoded 5706544 bytes +source-map-js 10717664 bytes +source-map-0.6.1 17446384 bytes +source-map-0.8.0 9701757 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 180 ops/sec ±0.34% (85 runs sampled) +trace-mapping: encoded JSON input x 364 ops/sec ±1.77% (89 runs sampled) +trace-mapping: decoded Object input x 3,116 ops/sec ±0.50% (96 runs sampled) +trace-mapping: encoded Object input x 410 ops/sec ±2.62% (85 runs sampled) +source-map-js: encoded Object input x 84.23 ops/sec ±0.91% (73 runs sampled) +source-map-0.6.1: encoded Object input x 37.21 ops/sec ±2.08% (51 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 3,952,212 ops/sec ±0.17% (98 runs sampled) +trace-mapping: encoded originalPositionFor x 3,487,468 ops/sec ±1.58% (90 runs sampled) +source-map-js: encoded originalPositionFor x 827,730 ops/sec ±0.78% (97 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 748,991 ops/sec ±0.53% (94 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 2,532,894 ops/sec ±0.57% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +babel.min.js.map - 347793 segments + +Memory Usage: +trace-mapping decoded 89832 bytes +trace-mapping encoded 35474640 bytes +source-map-js 51257176 bytes +source-map-0.6.1 63515664 bytes +source-map-0.8.0 42933752 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 15.41 ops/sec ±8.65% (34 runs sampled) +trace-mapping: encoded JSON input x 28.20 ops/sec ±12.87% (42 runs sampled) +trace-mapping: decoded Object input x 964 ops/sec ±0.36% (99 runs sampled) +trace-mapping: encoded Object input x 31.77 ops/sec ±13.79% (45 runs sampled) +source-map-js: encoded Object input x 6.45 ops/sec ±5.16% (21 runs sampled) +source-map-0.6.1: encoded Object input x 4.07 ops/sec ±5.24% (15 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 7,183,038 ops/sec ±0.58% (95 runs sampled) +trace-mapping: encoded originalPositionFor x 5,192,185 ops/sec ±0.41% (100 runs sampled) +source-map-js: encoded originalPositionFor x 4,259,489 ops/sec ±0.79% (94 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 3,742,629 ops/sec ±0.71% (95 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 6,270,211 ops/sec ±0.64% (94 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +preact.js.map - 1992 segments + +Memory Usage: +trace-mapping decoded 37128 bytes +trace-mapping encoded 247280 bytes +source-map-js 1143536 bytes +source-map-0.6.1 1290992 bytes +source-map-0.8.0 96544 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 3,483 ops/sec ±0.30% (98 runs sampled) +trace-mapping: encoded JSON input x 6,092 ops/sec ±0.18% (97 runs sampled) +trace-mapping: decoded Object input x 249,076 ops/sec ±0.24% (98 runs sampled) +trace-mapping: encoded Object input x 14,555 ops/sec ±0.48% (100 runs sampled) +source-map-js: encoded Object input x 2,447 ops/sec ±0.36% (99 runs sampled) +source-map-0.6.1: encoded Object input x 1,201 ops/sec ±0.57% (96 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 7,620,192 ops/sec ±0.09% (99 runs sampled) +trace-mapping: encoded originalPositionFor x 6,872,554 ops/sec ±0.30% (97 runs sampled) +source-map-js: encoded originalPositionFor x 2,489,570 ops/sec ±0.35% (94 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 1,698,633 ops/sec ±0.28% (98 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 4,015,644 ops/sec ±0.22% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +react.js.map - 5726 segments + +Memory Usage: +trace-mapping decoded 16176 bytes +trace-mapping encoded 681552 bytes +source-map-js 2418352 bytes +source-map-0.6.1 2443672 bytes +source-map-0.8.0 111768 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 1,720 ops/sec ±0.34% (98 runs sampled) +trace-mapping: encoded JSON input x 4,406 ops/sec ±0.35% (100 runs sampled) +trace-mapping: decoded Object input x 92,122 ops/sec ±0.10% (99 runs sampled) +trace-mapping: encoded Object input x 5,385 ops/sec ±0.37% (99 runs sampled) +source-map-js: encoded Object input x 794 ops/sec ±0.40% (98 runs sampled) +source-map-0.6.1: encoded Object input x 416 ops/sec ±0.54% (91 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed: +trace-mapping: decoded originalPositionFor x 32,759,519 ops/sec ±0.33% (100 runs sampled) +trace-mapping: encoded originalPositionFor x 31,116,306 ops/sec ±0.33% (97 runs sampled) +source-map-js: encoded originalPositionFor x 17,458,435 ops/sec ±0.44% (97 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 12,687,097 ops/sec ±0.43% (95 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 23,538,275 ops/sec ±0.38% (95 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor +``` + +[source-map]: https://www.npmjs.com/package/source-map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs new file mode 100644 index 0000000..917a330 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs @@ -0,0 +1,552 @@ +import { encode, decode } from '@jridgewell/sourcemap-codec'; +import resolveUri from '@jridgewell/resolve-uri'; + +function resolve(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 resolveUri(input, base); +} + +/** + * Removes everything after the last "/", but leaves the slash. + */ +function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} + +const COLUMN = 0; +const SOURCES_INDEX = 1; +const SOURCE_LINE = 2; +const SOURCE_COLUMN = 3; +const NAMES_INDEX = 4; +const REV_GENERATED_LINE = 1; +const REV_GENERATED_COLUMN = 2; + +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +let found = false; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like +// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. +// Numeric properties on objects are magically sorted in ascending order by the engine regardless of +// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending +// order when iterating with for-in. +function buildNullArray() { + return { __proto__: null }; +} + +const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return presortedDecodedMap(joined); +}; +function recurse(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } + else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection(map, mapUrl, mappings, sources, sourcesContent, names, lineOffset + offset.line, columnOffset + offset.column, sl, sc); + } +} +function addSection(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + if ('sections' in input) + return recurse(...arguments); + const map = new TraceMap(input, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) + append(sourcesContent, contents); + else + for (let i = 0; i < resolvedSources.length; i++) + sourcesContent.push(null); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) + return; + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) + return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push(seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); +} +function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) + arr[i] = []; + return arr[index]; +} + +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; +const LEAST_UPPER_BOUND = -1; +const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +let encodedMappings; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +let decodedMappings; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +let traceSegment; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +let originalPositionFor; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +let generatedPositionFor; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +let allGeneratedPositionsFor; +/** + * Iterates each mapping in generated position order. + */ +let eachMapping; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +let sourceContentFor; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +let presortedDecodedMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let decodedMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +let encodedMap; +class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} +(() => { + encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = encode(map._decoded))); + }; + decodedMappings = (map) => { + return (map._decoded || (map._decoded = decode(map._encoded))); + }; + traceSegment = (map, line, column) => { + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; + }; + originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (index === -1) + return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) + return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); + }; + allGeneratedPositionsFor = (map, { source, line, column, bias }) => { + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); + }; + generatedPositionFor = (map, { source, line, column, bias }) => { + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); + }; + eachMapping = (map, cb) => { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + sourceContentFor = (map, source) => { + const { sources, resolvedSources, sourcesContent } = map; + if (sourcesContent == null) + return null; + let index = sources.indexOf(source); + if (index === -1) + index = resolvedSources.indexOf(source); + return index === -1 ? null : sourcesContent[index]; + }; + presortedDecodedMap = (map, mapUrl) => { + const tracer = new TraceMap(clone(map, []), mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + decodedMap = (map) => { + return clone(map, decodedMappings(map)); + }; + encodedMap = (map) => { + return clone(map, encodedMappings(map)); + }; + function generatedPosition(map, source, line, column, bias, all) { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return all ? [] : GMapping(null, null); + const generated = (map._bySources || (map._bySources = buildBySources(decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const segments = generated[sourceIndex][line]; + if (segments == null) + return all ? [] : GMapping(null, null); + const memo = map._bySourceMemos[sourceIndex]; + if (all) + return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) + return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); + } +})(); +function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + }; +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function GMapping(line, column) { + return { line, column }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; +} +function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!found && bias === LEAST_UPPER_BOUND) + min++; + if (min === -1 || min === segments.length) + return []; + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = found ? column : segments[min][COLUMN]; + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!found) + min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} + +export { AnyMap, GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap, allGeneratedPositionsFor, decodedMap, decodedMappings, eachMapping, encodedMap, encodedMappings, generatedPositionFor, originalPositionFor, presortedDecodedMap, sourceContentFor, traceSegment }; +//# sourceMappingURL=trace-mapping.mjs.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map new file mode 100644 index 0000000..4d40aa1 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.mjs","sources":["../src/resolve.ts","../src/strip-filename.ts","../src/sourcemap-segment.ts","../src/sort.ts","../src/binary-search.ts","../src/by-source.ts","../src/any-map.ts","../src/trace-mapping.ts"],"sourcesContent":["import resolveUri from '@jridgewell/resolve-uri';\n\nexport default function resolve(input: string, base: string | undefined): string {\n // The base is always treated as a directory, if it's not empty.\n // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327\n // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401\n if (base && !base.endsWith('/')) base += '/';\n\n return resolveUri(input, base);\n}\n","/**\n * Removes everything after the last \"/\", but leaves the slash.\n */\nexport default function stripFilename(path: string | undefined | null): string {\n if (!path) return '';\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n","type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\ntype GeneratedLine = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n\nexport const REV_GENERATED_LINE = 1;\nexport const REV_GENERATED_COLUMN = 2;\n","import { COLUMN } from './sourcemap-segment';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\n\nexport default function maybeSort(\n mappings: SourceMapSegment[][],\n owned: boolean,\n): SourceMapSegment[][] {\n const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);\n if (unsortedIndex === mappings.length) return mappings;\n\n // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If\n // not, we do not want to modify the consumer's input array.\n if (!owned) mappings = mappings.slice();\n\n for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {\n mappings[i] = sortSegments(mappings[i], owned);\n }\n return mappings;\n}\n\nfunction nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {\n for (let i = start; i < mappings.length; i++) {\n if (!isSorted(mappings[i])) return i;\n }\n return mappings.length;\n}\n\nfunction isSorted(line: SourceMapSegment[]): boolean {\n for (let j = 1; j < line.length; j++) {\n if (line[j][COLUMN] < line[j - 1][COLUMN]) {\n return false;\n }\n }\n return true;\n}\n\nfunction sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {\n if (!owned) line = line.slice();\n return line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[COLUMN] - b[COLUMN];\n}\n","import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport { COLUMN } from './sourcemap-segment';\n\nexport type MemoState = {\n lastKey: number;\n lastNeedle: number;\n lastIndex: number;\n};\n\nexport let found = false;\n\n/**\n * A binary search implementation that returns the index if a match is found.\n * If no match is found, then the left-index (the index associated with the item that comes just\n * before the desired index) is returned. To maintain proper sort order, a splice would happen at\n * the next index:\n *\n * ```js\n * const array = [1, 3];\n * const needle = 2;\n * const index = binarySearch(array, needle, (item, needle) => item - needle);\n *\n * assert.equal(index, 0);\n * array.splice(index + 1, 0, needle);\n * assert.deepEqual(array, [1, 2, 3]);\n * ```\n */\nexport function binarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n low: number,\n high: number,\n): number {\n while (low <= high) {\n const mid = low + ((high - low) >> 1);\n const cmp = haystack[mid][COLUMN] - needle;\n\n if (cmp === 0) {\n found = true;\n return mid;\n }\n\n if (cmp < 0) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n found = false;\n return low - 1;\n}\n\nexport function upperBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index + 1; i < haystack.length; index = i++) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function lowerBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index - 1; i >= 0; index = i--) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function memoizedState(): MemoState {\n return {\n lastKey: -1,\n lastNeedle: -1,\n lastIndex: -1,\n };\n}\n\n/**\n * This overly complicated beast is just to record the last tested line/column and the resulting\n * index, allowing us to skip a few tests if mappings are monotonically increasing.\n */\nexport function memoizedBinarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n state: MemoState,\n key: number,\n): number {\n const { lastKey, lastNeedle, lastIndex } = state;\n\n let low = 0;\n let high = haystack.length - 1;\n if (key === lastKey) {\n if (needle === lastNeedle) {\n found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;\n return lastIndex;\n }\n\n if (needle >= lastNeedle) {\n // lastIndex may be -1 if the previous needle was not found.\n low = lastIndex === -1 ? 0 : lastIndex;\n } else {\n high = lastIndex;\n }\n }\n state.lastKey = key;\n state.lastNeedle = needle;\n\n return (state.lastIndex = binarySearch(haystack, needle, low, high));\n}\n","import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment';\nimport { memoizedBinarySearch, upperBound } from './binary-search';\n\nimport type { ReverseSegment, SourceMapSegment } from './sourcemap-segment';\nimport type { MemoState } from './binary-search';\n\nexport type Source = {\n __proto__: null;\n [line: number]: Exclude[];\n};\n\n// Rebuilds the original source files, with mappings that are ordered by source line/column instead\n// of generated line/column.\nexport default function buildBySources(\n decoded: readonly SourceMapSegment[][],\n memos: MemoState[],\n): Source[] {\n const sources: Source[] = memos.map(buildNullArray);\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n if (seg.length === 1) continue;\n\n const sourceIndex = seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n const originalSource = sources[sourceIndex];\n const originalLine = (originalSource[sourceLine] ||= []);\n const memo = memos[sourceIndex];\n\n // The binary search either found a match, or it found the left-index just before where the\n // segment should go. Either way, we want to insert after that. And there may be multiple\n // generated segments associated with an original location, so there may need to move several\n // indexes before we find where we need to insert.\n const index = upperBound(\n originalLine,\n sourceColumn,\n memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine),\n );\n\n insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]);\n }\n }\n\n return sources;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\n// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like\n// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.\n// Numeric properties on objects are magically sorted in ascending order by the engine regardless of\n// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending\n// order when iterating with for-in.\nfunction buildNullArray(): T {\n return { __proto__: null } as T;\n}\n","import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type {\n Section,\n SectionedSourceMap,\n DecodedSourceMap,\n SectionedSourceMapInput,\n Ro,\n} from './types';\nimport type { SourceMapSegment } from './sourcemap-segment';\n\ntype AnyMap = {\n new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n};\n\nexport const AnyMap: AnyMap = function (map, mapUrl) {\n const parsed =\n typeof map === 'string' ? (JSON.parse(map) as Exclude) : map;\n\n if (!('sections' in parsed)) return new TraceMap(parsed, mapUrl);\n\n const mappings: SourceMapSegment[][] = [];\n const sources: string[] = [];\n const sourcesContent: (string | null)[] = [];\n const names: string[] = [];\n\n recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity);\n\n const joined: DecodedSourceMap = {\n version: 3,\n file: parsed.file,\n names,\n sources,\n sourcesContent,\n mappings,\n };\n\n return presortedDecodedMap(joined);\n} as AnyMap;\n\nfunction recurse(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const { sections } = input;\n for (let i = 0; i < sections.length; i++) {\n const { map, offset } = sections[i];\n\n let sl = stopLine;\n let sc = stopColumn;\n if (i + 1 < sections.length) {\n const nextOffset = sections[i + 1].offset;\n sl = Math.min(stopLine, lineOffset + nextOffset.line);\n\n if (sl === stopLine) {\n sc = Math.min(stopColumn, columnOffset + nextOffset.column);\n } else if (sl < stopLine) {\n sc = columnOffset + nextOffset.column;\n }\n }\n\n addSection(\n map,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n lineOffset + offset.line,\n columnOffset + offset.column,\n sl,\n sc,\n );\n }\n}\n\nfunction addSection(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n if ('sections' in input) return recurse(...(arguments as unknown as Parameters));\n\n const map = new TraceMap(input, mapUrl);\n const sourcesOffset = sources.length;\n const namesOffset = names.length;\n const decoded = decodedMappings(map);\n const { resolvedSources, sourcesContent: contents } = map;\n\n append(sources, resolvedSources);\n append(names, map.names);\n if (contents) append(sourcesContent, contents);\n else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);\n\n for (let i = 0; i < decoded.length; i++) {\n const lineI = lineOffset + i;\n\n // We can only add so many lines before we step into the range that the next section's map\n // controls. When we get to the last line, then we'll start checking the segments to see if\n // they've crossed into the column range. But it may not have any columns that overstep, so we\n // still need to check that we don't overstep lines, too.\n if (lineI > stopLine) return;\n\n // The out line may already exist in mappings (if we're continuing the line started by a\n // previous section). Or, we may have jumped ahead several lines to start this section.\n const out = getLine(mappings, lineI);\n // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the\n // map can be multiple lines), it doesn't.\n const cOffset = i === 0 ? columnOffset : 0;\n\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n const column = cOffset + seg[COLUMN];\n\n // If this segment steps into the column range that the next section's map controls, we need\n // to stop early.\n if (lineI === stopLine && column >= stopColumn) return;\n\n if (seg.length === 1) {\n out.push([column]);\n continue;\n }\n\n const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n out.push(\n seg.length === 4\n ? [column, sourcesIndex, sourceLine, sourceColumn]\n : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]],\n );\n }\n }\n}\n\nfunction append(arr: T[], other: T[]) {\n for (let i = 0; i < other.length; i++) arr.push(other[i]);\n}\n\nfunction getLine(arr: T[][], index: number): T[] {\n for (let i = arr.length; i <= index; i++) arr[i] = [];\n return arr[index];\n}\n","import { encode, decode } from '@jridgewell/sourcemap-codec';\n\nimport resolve from './resolve';\nimport stripFilename from './strip-filename';\nimport maybeSort from './sort';\nimport buildBySources from './by-source';\nimport {\n memoizedState,\n memoizedBinarySearch,\n upperBound,\n lowerBound,\n found as bsFound,\n} from './binary-search';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n REV_GENERATED_LINE,\n REV_GENERATED_COLUMN,\n} from './sourcemap-segment';\n\nimport type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport type {\n SourceMapV3,\n DecodedSourceMap,\n EncodedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n SourceMapInput,\n Needle,\n SourceNeedle,\n SourceMap,\n EachMapping,\n Bias,\n} from './types';\nimport type { Source } from './by-source';\nimport type { MemoState } from './binary-search';\n\nexport type { SourceMapSegment } from './sourcemap-segment';\nexport type {\n SourceMapInput,\n SectionedSourceMapInput,\n DecodedSourceMap,\n EncodedSourceMap,\n SectionedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping as Mapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n EachMapping,\n} from './types';\n\nconst LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';\nconst COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';\n\nexport const LEAST_UPPER_BOUND = -1;\nexport const GREATEST_LOWER_BOUND = 1;\n\n/**\n * Returns the encoded (VLQ string) form of the SourceMap's mappings field.\n */\nexport let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings'];\n\n/**\n * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.\n */\nexport let decodedMappings: (map: TraceMap) => Readonly;\n\n/**\n * A low-level API to find the segment associated with a generated line/column (think, from a\n * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.\n */\nexport let traceSegment: (\n map: TraceMap,\n line: number,\n column: number,\n) => Readonly | null;\n\n/**\n * A higher-level API to find the source/line/column associated with a generated line/column\n * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in\n * `source-map` library.\n */\nexport let originalPositionFor: (\n map: TraceMap,\n needle: Needle,\n) => OriginalMapping | InvalidOriginalMapping;\n\n/**\n * Finds the generated line/column position of the provided source/line/column source position.\n */\nexport let generatedPositionFor: (\n map: TraceMap,\n needle: SourceNeedle,\n) => GeneratedMapping | InvalidGeneratedMapping;\n\n/**\n * Finds all generated line/column positions of the provided source/line/column source position.\n */\nexport let allGeneratedPositionsFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping[];\n\n/**\n * Iterates each mapping in generated position order.\n */\nexport let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void;\n\n/**\n * Retrieves the source content for a particular source, if its found. Returns null if not.\n */\nexport let sourceContentFor: (map: TraceMap, source: string) => string | null;\n\n/**\n * A helper that skips sorting of the input map's mappings array, which can be expensive for larger\n * maps.\n */\nexport let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let decodedMap: (\n map: TraceMap,\n) => Omit & { mappings: readonly SourceMapSegment[][] };\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let encodedMap: (map: TraceMap) => EncodedSourceMap;\n\nexport { AnyMap } from './any-map';\n\nexport class TraceMap implements SourceMap {\n declare version: SourceMapV3['version'];\n declare file: SourceMapV3['file'];\n declare names: SourceMapV3['names'];\n declare sourceRoot: SourceMapV3['sourceRoot'];\n declare sources: SourceMapV3['sources'];\n declare sourcesContent: SourceMapV3['sourcesContent'];\n\n declare resolvedSources: string[];\n private declare _encoded: string | undefined;\n\n private declare _decoded: SourceMapSegment[][] | undefined;\n private declare _decodedMemo: MemoState;\n\n private declare _bySources: Source[] | undefined;\n private declare _bySourceMemos: MemoState[] | undefined;\n\n constructor(map: SourceMapInput, mapUrl?: string | null) {\n const isString = typeof map === 'string';\n\n if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;\n\n const parsed = (isString ? JSON.parse(map) : map) as DecodedSourceMap | EncodedSourceMap;\n\n const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;\n this.version = version;\n this.file = file;\n this.names = names;\n this.sourceRoot = sourceRoot;\n this.sources = sources;\n this.sourcesContent = sourcesContent;\n\n const from = resolve(sourceRoot || '', stripFilename(mapUrl));\n this.resolvedSources = sources.map((s) => resolve(s || '', from));\n\n const { mappings } = parsed;\n if (typeof mappings === 'string') {\n this._encoded = mappings;\n this._decoded = undefined;\n } else {\n this._encoded = undefined;\n this._decoded = maybeSort(mappings, isString);\n }\n\n this._decodedMemo = memoizedState();\n this._bySources = undefined;\n this._bySourceMemos = undefined;\n }\n\n static {\n encodedMappings = (map) => {\n return (map._encoded ??= encode(map._decoded!));\n };\n\n decodedMappings = (map) => {\n return (map._decoded ||= decode(map._encoded!));\n };\n\n traceSegment = (map, line, column) => {\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return null;\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n GREATEST_LOWER_BOUND,\n );\n\n return index === -1 ? null : segments[index];\n };\n\n originalPositionFor = (map, { line, column, bias }) => {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return OMapping(null, null, null, null);\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n bias || GREATEST_LOWER_BOUND,\n );\n\n if (index === -1) return OMapping(null, null, null, null);\n\n const segment = segments[index];\n if (segment.length === 1) return OMapping(null, null, null, null);\n\n const { names, resolvedSources } = map;\n return OMapping(\n resolvedSources[segment[SOURCES_INDEX]],\n segment[SOURCE_LINE] + 1,\n segment[SOURCE_COLUMN],\n segment.length === 5 ? names[segment[NAMES_INDEX]] : null,\n );\n };\n\n allGeneratedPositionsFor = (map, { source, line, column, bias }) => {\n // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.\n return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);\n };\n\n generatedPositionFor = (map, { source, line, column, bias }) => {\n return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);\n };\n\n eachMapping = (map, cb) => {\n const decoded = decodedMappings(map);\n const { names, resolvedSources } = map;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generatedLine = i + 1;\n const generatedColumn = seg[0];\n let source = null;\n let originalLine = null;\n let originalColumn = null;\n let name = null;\n if (seg.length !== 1) {\n source = resolvedSources[seg[1]];\n originalLine = seg[2] + 1;\n originalColumn = seg[3];\n }\n if (seg.length === 5) name = names[seg[4]];\n\n cb({\n generatedLine,\n generatedColumn,\n source,\n originalLine,\n originalColumn,\n name,\n } as EachMapping);\n }\n }\n };\n\n sourceContentFor = (map, source) => {\n const { sources, resolvedSources, sourcesContent } = map;\n if (sourcesContent == null) return null;\n\n let index = sources.indexOf(source);\n if (index === -1) index = resolvedSources.indexOf(source);\n\n return index === -1 ? null : sourcesContent[index];\n };\n\n presortedDecodedMap = (map, mapUrl) => {\n const tracer = new TraceMap(clone(map, []), mapUrl);\n tracer._decoded = map.mappings;\n return tracer;\n };\n\n decodedMap = (map) => {\n return clone(map, decodedMappings(map));\n };\n\n encodedMap = (map) => {\n return clone(map, encodedMappings(map));\n };\n\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: false,\n ): GeneratedMapping | InvalidGeneratedMapping;\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: true,\n ): GeneratedMapping[];\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: boolean,\n ): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const { sources, resolvedSources } = map;\n let sourceIndex = sources.indexOf(source);\n if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);\n if (sourceIndex === -1) return all ? [] : GMapping(null, null);\n\n const generated = (map._bySources ||= buildBySources(\n decodedMappings(map),\n (map._bySourceMemos = sources.map(memoizedState)),\n ));\n\n const segments = generated[sourceIndex][line];\n if (segments == null) return all ? [] : GMapping(null, null);\n\n const memo = map._bySourceMemos![sourceIndex];\n\n if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);\n\n const index = traceSegmentInternal(segments, memo, line, column, bias);\n if (index === -1) return GMapping(null, null);\n\n const segment = segments[index];\n return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);\n }\n }\n}\n\nfunction clone(\n map: TraceMap | DecodedSourceMap | EncodedSourceMap,\n mappings: T,\n): T extends string ? EncodedSourceMap : DecodedSourceMap {\n return {\n version: map.version,\n file: map.file,\n names: map.names,\n sourceRoot: map.sourceRoot,\n sources: map.sources,\n sourcesContent: map.sourcesContent,\n mappings,\n } as any;\n}\n\nfunction OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;\nfunction OMapping(\n source: string,\n line: number,\n column: number,\n name: string | null,\n): OriginalMapping;\nfunction OMapping(\n source: string | null,\n line: number | null,\n column: number | null,\n name: string | null,\n): OriginalMapping | InvalidOriginalMapping {\n return { source, line, column, name } as any;\n}\n\nfunction GMapping(line: null, column: null): InvalidGeneratedMapping;\nfunction GMapping(line: number, column: number): GeneratedMapping;\nfunction GMapping(\n line: number | null,\n column: number | null,\n): GeneratedMapping | InvalidGeneratedMapping {\n return { line, column } as any;\n}\n\nfunction traceSegmentInternal(\n segments: SourceMapSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: SourceMapSegment[] | ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number {\n let index = memoizedBinarySearch(segments, column, memo, line);\n if (bsFound) {\n index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);\n } else if (bias === LEAST_UPPER_BOUND) index++;\n\n if (index === -1 || index === segments.length) return -1;\n return index;\n}\n\nfunction sliceGeneratedPositions(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): GeneratedMapping[] {\n let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);\n\n // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in\n // insertion order) segment that matched. Even if we did respect the bias when tracing, we would\n // still need to call `lowerBound()` to find the first segment, which is slower than just looking\n // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the\n // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to\n // match LEAST_UPPER_BOUND.\n if (!bsFound && bias === LEAST_UPPER_BOUND) min++;\n\n if (min === -1 || min === segments.length) return [];\n\n // We may have found the segment that started at an earlier column. If this is the case, then we\n // need to slice all generated segments that match _that_ column, because all such segments span\n // to our desired column.\n const matchedColumn = bsFound ? column : segments[min][COLUMN];\n\n // The binary search is not guaranteed to find the lower bound when a match wasn't found.\n if (!bsFound) min = lowerBound(segments, matchedColumn, min);\n const max = upperBound(segments, matchedColumn, min);\n\n const result = [];\n for (; min <= max; min++) {\n const segment = segments[min];\n result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));\n }\n return result;\n}\n"],"names":["bsFound"],"mappings":";;;AAEc,SAAU,OAAO,CAAC,KAAa,EAAE,IAAwB,EAAA;;;;IAIrE,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,IAAI,IAAI,GAAG,CAAC;AAE7C,IAAA,OAAO,UAAU,CAAC,KA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AC9B,QAA0B,EAC1B,IAAe,EACf,IAAY,EACZ,MAAc,EACd,IAAU,EAAA;AAEV,IAAA,IAAI,GAAG,GAAG,oBAAoB,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,oBAAoB,CAAC,CAAC;;;;;;;AAQnF,IAAA,IAAI,CAACA,KAAO,IAAI,IAAI,KAAK,iBAAiB;AAAE,QAAA,GAAG,EAAE,CAAC;IAElD,IAAI,GAAG,KAAK,CAAC,CAAC,IAAI,GAAG,KAAK,QAAQ,CAAC,MAAM;AAAE,QAAA,OAAO,EAAE,CAAC;;;;AAKrD,IAAA,MAAM,aAAa,GAAGA,KAAO,GAAG,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC;;AAG/D,IAAA,IAAI,CAACA,KAAO;QAAE,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;IAC7D,MAAM,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,CAAC;IAErD,MAAM,MAAM,GAAG,EAAE,CAAC;AAClB,IAAA,OAAO,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE,EAAE;AACxB,QAAA,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;AAC9B,QAAA,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,GAAG,CAAC,EAAE,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC;AACvF,KAAA;AACD,IAAA,OAAO,MAAM,CAAC;AAChB;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js new file mode 100644 index 0000000..a3251f1 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js @@ -0,0 +1,566 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/sourcemap-codec'), require('@jridgewell/resolve-uri')) : + typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/sourcemap-codec', '@jridgewell/resolve-uri'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.traceMapping = {}, global.sourcemapCodec, global.resolveURI)); +})(this, (function (exports, sourcemapCodec, resolveUri) { 'use strict'; + + function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + + var resolveUri__default = /*#__PURE__*/_interopDefaultLegacy(resolveUri); + + function resolve(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 resolveUri__default["default"](input, base); + } + + /** + * Removes everything after the last "/", but leaves the slash. + */ + function stripFilename(path) { + if (!path) + return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + + const COLUMN = 0; + const SOURCES_INDEX = 1; + const SOURCE_LINE = 2; + const SOURCE_COLUMN = 3; + const NAMES_INDEX = 4; + const REV_GENERATED_LINE = 1; + const REV_GENERATED_COLUMN = 2; + + function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) + return mappings; + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) + mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; + } + function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) + return i; + } + return mappings.length; + } + function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; + } + function sortSegments(line, owned) { + if (!owned) + line = line.slice(); + return line.sort(sortComparator); + } + function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; + } + + let found = false; + /** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ + function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } + else { + high = mid - 1; + } + } + found = false; + return low - 1; + } + function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) + break; + } + return index; + } + function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; + } + /** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ + function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } + else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return (state.lastIndex = binarySearch(haystack, needle, low, high)); + } + + // Rebuilds the original source files, with mappings that are ordered by source line/column instead + // of generated line/column. + function buildBySources(decoded, memos) { + const sources = memos.map(buildNullArray); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) + continue; + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const originalSource = sources[sourceIndex]; + const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = [])); + const memo = memos[sourceIndex]; + // The binary search either found a match, or it found the left-index just before where the + // segment should go. Either way, we want to insert after that. And there may be multiple + // generated segments associated with an original location, so there may need to move several + // indexes before we find where we need to insert. + const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine)); + insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]); + } + } + return sources; + } + function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; + } + // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like + // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations. + // Numeric properties on objects are magically sorted in ascending order by the engine regardless of + // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending + // order when iterating with for-in. + function buildNullArray() { + return { __proto__: null }; + } + + const AnyMap = function (map, mapUrl) { + const parsed = typeof map === 'string' ? JSON.parse(map) : map; + if (!('sections' in parsed)) + return new TraceMap(parsed, mapUrl); + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + }; + return exports.presortedDecodedMap(joined); + }; + function recurse(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } + else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection(map, mapUrl, mappings, sources, sourcesContent, names, lineOffset + offset.line, columnOffset + offset.column, sl, sc); + } + } + function addSection(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) { + if ('sections' in input) + return recurse(...arguments); + const map = new TraceMap(input, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = exports.decodedMappings(map); + const { resolvedSources, sourcesContent: contents } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) + append(sourcesContent, contents); + else + for (let i = 0; i < resolvedSources.length; i++) + sourcesContent.push(null); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) + return; + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) + return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push(seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]); + } + } + } + function append(arr, other) { + for (let i = 0; i < other.length; i++) + arr.push(other[i]); + } + function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) + arr[i] = []; + return arr[index]; + } + + const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; + const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; + const LEAST_UPPER_BOUND = -1; + const GREATEST_LOWER_BOUND = 1; + /** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ + exports.encodedMappings = void 0; + /** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ + exports.decodedMappings = void 0; + /** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ + exports.traceSegment = void 0; + /** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ + exports.originalPositionFor = void 0; + /** + * Finds the generated line/column position of the provided source/line/column source position. + */ + exports.generatedPositionFor = void 0; + /** + * Finds all generated line/column positions of the provided source/line/column source position. + */ + exports.allGeneratedPositionsFor = void 0; + /** + * Iterates each mapping in generated position order. + */ + exports.eachMapping = void 0; + /** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ + exports.sourceContentFor = void 0; + /** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ + exports.presortedDecodedMap = void 0; + /** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.decodedMap = void 0; + /** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ + exports.encodedMap = void 0; + class TraceMap { + constructor(map, mapUrl) { + const isString = typeof map === 'string'; + if (!isString && map._decodedMemo) + return map; + const parsed = (isString ? JSON.parse(map) : map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + const from = resolve(sourceRoot || '', stripFilename(mapUrl)); + this.resolvedSources = sources.map((s) => resolve(s || '', from)); + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } + else { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } + } + (() => { + exports.encodedMappings = (map) => { + var _a; + return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = sourcemapCodec.encode(map._decoded))); + }; + exports.decodedMappings = (map) => { + return (map._decoded || (map._decoded = sourcemapCodec.decode(map._encoded))); + }; + exports.traceSegment = (map, line, column) => { + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return null; + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, GREATEST_LOWER_BOUND); + return index === -1 ? null : segments[index]; + }; + exports.originalPositionFor = (map, { line, column, bias }) => { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const decoded = exports.decodedMappings(map); + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) + return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND); + if (index === -1) + return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) + return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null); + }; + exports.allGeneratedPositionsFor = (map, { source, line, column, bias }) => { + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); + }; + exports.generatedPositionFor = (map, { source, line, column, bias }) => { + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); + }; + exports.eachMapping = (map, cb) => { + const decoded = exports.decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) + name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + }); + } + } + }; + exports.sourceContentFor = (map, source) => { + const { sources, resolvedSources, sourcesContent } = map; + if (sourcesContent == null) + return null; + let index = sources.indexOf(source); + if (index === -1) + index = resolvedSources.indexOf(source); + return index === -1 ? null : sourcesContent[index]; + }; + exports.presortedDecodedMap = (map, mapUrl) => { + const tracer = new TraceMap(clone(map, []), mapUrl); + tracer._decoded = map.mappings; + return tracer; + }; + exports.decodedMap = (map) => { + return clone(map, exports.decodedMappings(map)); + }; + exports.encodedMap = (map) => { + return clone(map, exports.encodedMappings(map)); + }; + function generatedPosition(map, source, line, column, bias, all) { + line--; + if (line < 0) + throw new Error(LINE_GTR_ZERO); + if (column < 0) + throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) + sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) + return all ? [] : GMapping(null, null); + const generated = (map._bySources || (map._bySources = buildBySources(exports.decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState))))); + const segments = generated[sourceIndex][line]; + if (segments == null) + return all ? [] : GMapping(null, null); + const memo = map._bySourceMemos[sourceIndex]; + if (all) + return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) + return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); + } + })(); + function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + }; + } + function OMapping(source, line, column, name) { + return { source, line, column, name }; + } + function GMapping(line, column) { + return { line, column }; + } + function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } + else if (bias === LEAST_UPPER_BOUND) + index++; + if (index === -1 || index === segments.length) + return -1; + return index; + } + function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!found && bias === LEAST_UPPER_BOUND) + min++; + if (min === -1 || min === segments.length) + return []; + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = found ? column : segments[min][COLUMN]; + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!found) + min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; + } + + exports.AnyMap = AnyMap; + exports.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND; + exports.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND; + exports.TraceMap = TraceMap; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); +//# sourceMappingURL=trace-mapping.umd.js.map diff --git a/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map new file mode 100644 index 0000000..fee1219 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.umd.js","sources":["../src/resolve.ts","../src/strip-filename.ts","../src/sourcemap-segment.ts","../src/sort.ts","../src/binary-search.ts","../src/by-source.ts","../src/any-map.ts","../src/trace-mapping.ts"],"sourcesContent":["import resolveUri from '@jridgewell/resolve-uri';\n\nexport default function resolve(input: string, base: string | undefined): string {\n // The base is always treated as a directory, if it's not empty.\n // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327\n // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401\n if (base && !base.endsWith('/')) base += '/';\n\n return resolveUri(input, base);\n}\n","/**\n * Removes everything after the last \"/\", but leaves the slash.\n */\nexport default function stripFilename(path: string | undefined | null): string {\n if (!path) return '';\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n","type GeneratedColumn = number;\ntype SourcesIndex = number;\ntype SourceLine = number;\ntype SourceColumn = number;\ntype NamesIndex = number;\n\ntype GeneratedLine = number;\n\nexport type SourceMapSegment =\n | [GeneratedColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn]\n | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];\n\nexport type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn];\n\nexport const COLUMN = 0;\nexport const SOURCES_INDEX = 1;\nexport const SOURCE_LINE = 2;\nexport const SOURCE_COLUMN = 3;\nexport const NAMES_INDEX = 4;\n\nexport const REV_GENERATED_LINE = 1;\nexport const REV_GENERATED_COLUMN = 2;\n","import { COLUMN } from './sourcemap-segment';\n\nimport type { SourceMapSegment } from './sourcemap-segment';\n\nexport default function maybeSort(\n mappings: SourceMapSegment[][],\n owned: boolean,\n): SourceMapSegment[][] {\n const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);\n if (unsortedIndex === mappings.length) return mappings;\n\n // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If\n // not, we do not want to modify the consumer's input array.\n if (!owned) mappings = mappings.slice();\n\n for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {\n mappings[i] = sortSegments(mappings[i], owned);\n }\n return mappings;\n}\n\nfunction nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number {\n for (let i = start; i < mappings.length; i++) {\n if (!isSorted(mappings[i])) return i;\n }\n return mappings.length;\n}\n\nfunction isSorted(line: SourceMapSegment[]): boolean {\n for (let j = 1; j < line.length; j++) {\n if (line[j][COLUMN] < line[j - 1][COLUMN]) {\n return false;\n }\n }\n return true;\n}\n\nfunction sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] {\n if (!owned) line = line.slice();\n return line.sort(sortComparator);\n}\n\nfunction sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {\n return a[COLUMN] - b[COLUMN];\n}\n","import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport { COLUMN } from './sourcemap-segment';\n\nexport type MemoState = {\n lastKey: number;\n lastNeedle: number;\n lastIndex: number;\n};\n\nexport let found = false;\n\n/**\n * A binary search implementation that returns the index if a match is found.\n * If no match is found, then the left-index (the index associated with the item that comes just\n * before the desired index) is returned. To maintain proper sort order, a splice would happen at\n * the next index:\n *\n * ```js\n * const array = [1, 3];\n * const needle = 2;\n * const index = binarySearch(array, needle, (item, needle) => item - needle);\n *\n * assert.equal(index, 0);\n * array.splice(index + 1, 0, needle);\n * assert.deepEqual(array, [1, 2, 3]);\n * ```\n */\nexport function binarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n low: number,\n high: number,\n): number {\n while (low <= high) {\n const mid = low + ((high - low) >> 1);\n const cmp = haystack[mid][COLUMN] - needle;\n\n if (cmp === 0) {\n found = true;\n return mid;\n }\n\n if (cmp < 0) {\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n found = false;\n return low - 1;\n}\n\nexport function upperBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index + 1; i < haystack.length; index = i++) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function lowerBound(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n index: number,\n): number {\n for (let i = index - 1; i >= 0; index = i--) {\n if (haystack[i][COLUMN] !== needle) break;\n }\n return index;\n}\n\nexport function memoizedState(): MemoState {\n return {\n lastKey: -1,\n lastNeedle: -1,\n lastIndex: -1,\n };\n}\n\n/**\n * This overly complicated beast is just to record the last tested line/column and the resulting\n * index, allowing us to skip a few tests if mappings are monotonically increasing.\n */\nexport function memoizedBinarySearch(\n haystack: SourceMapSegment[] | ReverseSegment[],\n needle: number,\n state: MemoState,\n key: number,\n): number {\n const { lastKey, lastNeedle, lastIndex } = state;\n\n let low = 0;\n let high = haystack.length - 1;\n if (key === lastKey) {\n if (needle === lastNeedle) {\n found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;\n return lastIndex;\n }\n\n if (needle >= lastNeedle) {\n // lastIndex may be -1 if the previous needle was not found.\n low = lastIndex === -1 ? 0 : lastIndex;\n } else {\n high = lastIndex;\n }\n }\n state.lastKey = key;\n state.lastNeedle = needle;\n\n return (state.lastIndex = binarySearch(haystack, needle, low, high));\n}\n","import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment';\nimport { memoizedBinarySearch, upperBound } from './binary-search';\n\nimport type { ReverseSegment, SourceMapSegment } from './sourcemap-segment';\nimport type { MemoState } from './binary-search';\n\nexport type Source = {\n __proto__: null;\n [line: number]: Exclude[];\n};\n\n// Rebuilds the original source files, with mappings that are ordered by source line/column instead\n// of generated line/column.\nexport default function buildBySources(\n decoded: readonly SourceMapSegment[][],\n memos: MemoState[],\n): Source[] {\n const sources: Source[] = memos.map(buildNullArray);\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n if (seg.length === 1) continue;\n\n const sourceIndex = seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n const originalSource = sources[sourceIndex];\n const originalLine = (originalSource[sourceLine] ||= []);\n const memo = memos[sourceIndex];\n\n // The binary search either found a match, or it found the left-index just before where the\n // segment should go. Either way, we want to insert after that. And there may be multiple\n // generated segments associated with an original location, so there may need to move several\n // indexes before we find where we need to insert.\n const index = upperBound(\n originalLine,\n sourceColumn,\n memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine),\n );\n\n insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]);\n }\n }\n\n return sources;\n}\n\nfunction insert(array: T[], index: number, value: T) {\n for (let i = array.length; i > index; i--) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n}\n\n// Null arrays allow us to use ordered index keys without actually allocating contiguous memory like\n// a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.\n// Numeric properties on objects are magically sorted in ascending order by the engine regardless of\n// the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending\n// order when iterating with for-in.\nfunction buildNullArray(): T {\n return { __proto__: null } as T;\n}\n","import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n} from './sourcemap-segment';\n\nimport type {\n Section,\n SectionedSourceMap,\n DecodedSourceMap,\n SectionedSourceMapInput,\n Ro,\n} from './types';\nimport type { SourceMapSegment } from './sourcemap-segment';\n\ntype AnyMap = {\n new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap;\n};\n\nexport const AnyMap: AnyMap = function (map, mapUrl) {\n const parsed =\n typeof map === 'string' ? (JSON.parse(map) as Exclude) : map;\n\n if (!('sections' in parsed)) return new TraceMap(parsed, mapUrl);\n\n const mappings: SourceMapSegment[][] = [];\n const sources: string[] = [];\n const sourcesContent: (string | null)[] = [];\n const names: string[] = [];\n\n recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity);\n\n const joined: DecodedSourceMap = {\n version: 3,\n file: parsed.file,\n names,\n sources,\n sourcesContent,\n mappings,\n };\n\n return presortedDecodedMap(joined);\n} as AnyMap;\n\nfunction recurse(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n const { sections } = input;\n for (let i = 0; i < sections.length; i++) {\n const { map, offset } = sections[i];\n\n let sl = stopLine;\n let sc = stopColumn;\n if (i + 1 < sections.length) {\n const nextOffset = sections[i + 1].offset;\n sl = Math.min(stopLine, lineOffset + nextOffset.line);\n\n if (sl === stopLine) {\n sc = Math.min(stopColumn, columnOffset + nextOffset.column);\n } else if (sl < stopLine) {\n sc = columnOffset + nextOffset.column;\n }\n }\n\n addSection(\n map,\n mapUrl,\n mappings,\n sources,\n sourcesContent,\n names,\n lineOffset + offset.line,\n columnOffset + offset.column,\n sl,\n sc,\n );\n }\n}\n\nfunction addSection(\n input: Ro,\n mapUrl: string | null | undefined,\n mappings: SourceMapSegment[][],\n sources: string[],\n sourcesContent: (string | null)[],\n names: string[],\n lineOffset: number,\n columnOffset: number,\n stopLine: number,\n stopColumn: number,\n) {\n if ('sections' in input) return recurse(...(arguments as unknown as Parameters));\n\n const map = new TraceMap(input, mapUrl);\n const sourcesOffset = sources.length;\n const namesOffset = names.length;\n const decoded = decodedMappings(map);\n const { resolvedSources, sourcesContent: contents } = map;\n\n append(sources, resolvedSources);\n append(names, map.names);\n if (contents) append(sourcesContent, contents);\n else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null);\n\n for (let i = 0; i < decoded.length; i++) {\n const lineI = lineOffset + i;\n\n // We can only add so many lines before we step into the range that the next section's map\n // controls. When we get to the last line, then we'll start checking the segments to see if\n // they've crossed into the column range. But it may not have any columns that overstep, so we\n // still need to check that we don't overstep lines, too.\n if (lineI > stopLine) return;\n\n // The out line may already exist in mappings (if we're continuing the line started by a\n // previous section). Or, we may have jumped ahead several lines to start this section.\n const out = getLine(mappings, lineI);\n // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the\n // map can be multiple lines), it doesn't.\n const cOffset = i === 0 ? columnOffset : 0;\n\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n const column = cOffset + seg[COLUMN];\n\n // If this segment steps into the column range that the next section's map controls, we need\n // to stop early.\n if (lineI === stopLine && column >= stopColumn) return;\n\n if (seg.length === 1) {\n out.push([column]);\n continue;\n }\n\n const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];\n const sourceLine = seg[SOURCE_LINE];\n const sourceColumn = seg[SOURCE_COLUMN];\n out.push(\n seg.length === 4\n ? [column, sourcesIndex, sourceLine, sourceColumn]\n : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]],\n );\n }\n }\n}\n\nfunction append(arr: T[], other: T[]) {\n for (let i = 0; i < other.length; i++) arr.push(other[i]);\n}\n\nfunction getLine(arr: T[][], index: number): T[] {\n for (let i = arr.length; i <= index; i++) arr[i] = [];\n return arr[index];\n}\n","import { encode, decode } from '@jridgewell/sourcemap-codec';\n\nimport resolve from './resolve';\nimport stripFilename from './strip-filename';\nimport maybeSort from './sort';\nimport buildBySources from './by-source';\nimport {\n memoizedState,\n memoizedBinarySearch,\n upperBound,\n lowerBound,\n found as bsFound,\n} from './binary-search';\nimport {\n COLUMN,\n SOURCES_INDEX,\n SOURCE_LINE,\n SOURCE_COLUMN,\n NAMES_INDEX,\n REV_GENERATED_LINE,\n REV_GENERATED_COLUMN,\n} from './sourcemap-segment';\n\nimport type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';\nimport type {\n SourceMapV3,\n DecodedSourceMap,\n EncodedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n SourceMapInput,\n Needle,\n SourceNeedle,\n SourceMap,\n EachMapping,\n Bias,\n} from './types';\nimport type { Source } from './by-source';\nimport type { MemoState } from './binary-search';\n\nexport type { SourceMapSegment } from './sourcemap-segment';\nexport type {\n SourceMapInput,\n SectionedSourceMapInput,\n DecodedSourceMap,\n EncodedSourceMap,\n SectionedSourceMap,\n InvalidOriginalMapping,\n OriginalMapping as Mapping,\n OriginalMapping,\n InvalidGeneratedMapping,\n GeneratedMapping,\n EachMapping,\n} from './types';\n\nconst LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';\nconst COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';\n\nexport const LEAST_UPPER_BOUND = -1;\nexport const GREATEST_LOWER_BOUND = 1;\n\n/**\n * Returns the encoded (VLQ string) form of the SourceMap's mappings field.\n */\nexport let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings'];\n\n/**\n * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.\n */\nexport let decodedMappings: (map: TraceMap) => Readonly;\n\n/**\n * A low-level API to find the segment associated with a generated line/column (think, from a\n * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.\n */\nexport let traceSegment: (\n map: TraceMap,\n line: number,\n column: number,\n) => Readonly | null;\n\n/**\n * A higher-level API to find the source/line/column associated with a generated line/column\n * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in\n * `source-map` library.\n */\nexport let originalPositionFor: (\n map: TraceMap,\n needle: Needle,\n) => OriginalMapping | InvalidOriginalMapping;\n\n/**\n * Finds the generated line/column position of the provided source/line/column source position.\n */\nexport let generatedPositionFor: (\n map: TraceMap,\n needle: SourceNeedle,\n) => GeneratedMapping | InvalidGeneratedMapping;\n\n/**\n * Finds all generated line/column positions of the provided source/line/column source position.\n */\nexport let allGeneratedPositionsFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping[];\n\n/**\n * Iterates each mapping in generated position order.\n */\nexport let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void;\n\n/**\n * Retrieves the source content for a particular source, if its found. Returns null if not.\n */\nexport let sourceContentFor: (map: TraceMap, source: string) => string | null;\n\n/**\n * A helper that skips sorting of the input map's mappings array, which can be expensive for larger\n * maps.\n */\nexport let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap;\n\n/**\n * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let decodedMap: (\n map: TraceMap,\n) => Omit & { mappings: readonly SourceMapSegment[][] };\n\n/**\n * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects\n * a sourcemap, or to JSON.stringify.\n */\nexport let encodedMap: (map: TraceMap) => EncodedSourceMap;\n\nexport { AnyMap } from './any-map';\n\nexport class TraceMap implements SourceMap {\n declare version: SourceMapV3['version'];\n declare file: SourceMapV3['file'];\n declare names: SourceMapV3['names'];\n declare sourceRoot: SourceMapV3['sourceRoot'];\n declare sources: SourceMapV3['sources'];\n declare sourcesContent: SourceMapV3['sourcesContent'];\n\n declare resolvedSources: string[];\n private declare _encoded: string | undefined;\n\n private declare _decoded: SourceMapSegment[][] | undefined;\n private declare _decodedMemo: MemoState;\n\n private declare _bySources: Source[] | undefined;\n private declare _bySourceMemos: MemoState[] | undefined;\n\n constructor(map: SourceMapInput, mapUrl?: string | null) {\n const isString = typeof map === 'string';\n\n if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;\n\n const parsed = (isString ? JSON.parse(map) : map) as DecodedSourceMap | EncodedSourceMap;\n\n const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;\n this.version = version;\n this.file = file;\n this.names = names;\n this.sourceRoot = sourceRoot;\n this.sources = sources;\n this.sourcesContent = sourcesContent;\n\n const from = resolve(sourceRoot || '', stripFilename(mapUrl));\n this.resolvedSources = sources.map((s) => resolve(s || '', from));\n\n const { mappings } = parsed;\n if (typeof mappings === 'string') {\n this._encoded = mappings;\n this._decoded = undefined;\n } else {\n this._encoded = undefined;\n this._decoded = maybeSort(mappings, isString);\n }\n\n this._decodedMemo = memoizedState();\n this._bySources = undefined;\n this._bySourceMemos = undefined;\n }\n\n static {\n encodedMappings = (map) => {\n return (map._encoded ??= encode(map._decoded!));\n };\n\n decodedMappings = (map) => {\n return (map._decoded ||= decode(map._encoded!));\n };\n\n traceSegment = (map, line, column) => {\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return null;\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n GREATEST_LOWER_BOUND,\n );\n\n return index === -1 ? null : segments[index];\n };\n\n originalPositionFor = (map, { line, column, bias }) => {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const decoded = decodedMappings(map);\n\n // It's common for parent source maps to have pointers to lines that have no\n // mapping (like a \"//# sourceMappingURL=\") at the end of the child file.\n if (line >= decoded.length) return OMapping(null, null, null, null);\n\n const segments = decoded[line];\n const index = traceSegmentInternal(\n segments,\n map._decodedMemo,\n line,\n column,\n bias || GREATEST_LOWER_BOUND,\n );\n\n if (index === -1) return OMapping(null, null, null, null);\n\n const segment = segments[index];\n if (segment.length === 1) return OMapping(null, null, null, null);\n\n const { names, resolvedSources } = map;\n return OMapping(\n resolvedSources[segment[SOURCES_INDEX]],\n segment[SOURCE_LINE] + 1,\n segment[SOURCE_COLUMN],\n segment.length === 5 ? names[segment[NAMES_INDEX]] : null,\n );\n };\n\n allGeneratedPositionsFor = (map, { source, line, column, bias }) => {\n // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.\n return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);\n };\n\n generatedPositionFor = (map, { source, line, column, bias }) => {\n return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);\n };\n\n eachMapping = (map, cb) => {\n const decoded = decodedMappings(map);\n const { names, resolvedSources } = map;\n\n for (let i = 0; i < decoded.length; i++) {\n const line = decoded[i];\n for (let j = 0; j < line.length; j++) {\n const seg = line[j];\n\n const generatedLine = i + 1;\n const generatedColumn = seg[0];\n let source = null;\n let originalLine = null;\n let originalColumn = null;\n let name = null;\n if (seg.length !== 1) {\n source = resolvedSources[seg[1]];\n originalLine = seg[2] + 1;\n originalColumn = seg[3];\n }\n if (seg.length === 5) name = names[seg[4]];\n\n cb({\n generatedLine,\n generatedColumn,\n source,\n originalLine,\n originalColumn,\n name,\n } as EachMapping);\n }\n }\n };\n\n sourceContentFor = (map, source) => {\n const { sources, resolvedSources, sourcesContent } = map;\n if (sourcesContent == null) return null;\n\n let index = sources.indexOf(source);\n if (index === -1) index = resolvedSources.indexOf(source);\n\n return index === -1 ? null : sourcesContent[index];\n };\n\n presortedDecodedMap = (map, mapUrl) => {\n const tracer = new TraceMap(clone(map, []), mapUrl);\n tracer._decoded = map.mappings;\n return tracer;\n };\n\n decodedMap = (map) => {\n return clone(map, decodedMappings(map));\n };\n\n encodedMap = (map) => {\n return clone(map, encodedMappings(map));\n };\n\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: false,\n ): GeneratedMapping | InvalidGeneratedMapping;\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: true,\n ): GeneratedMapping[];\n function generatedPosition(\n map: TraceMap,\n source: string,\n line: number,\n column: number,\n bias: Bias,\n all: boolean,\n ): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {\n line--;\n if (line < 0) throw new Error(LINE_GTR_ZERO);\n if (column < 0) throw new Error(COL_GTR_EQ_ZERO);\n\n const { sources, resolvedSources } = map;\n let sourceIndex = sources.indexOf(source);\n if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);\n if (sourceIndex === -1) return all ? [] : GMapping(null, null);\n\n const generated = (map._bySources ||= buildBySources(\n decodedMappings(map),\n (map._bySourceMemos = sources.map(memoizedState)),\n ));\n\n const segments = generated[sourceIndex][line];\n if (segments == null) return all ? [] : GMapping(null, null);\n\n const memo = map._bySourceMemos![sourceIndex];\n\n if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);\n\n const index = traceSegmentInternal(segments, memo, line, column, bias);\n if (index === -1) return GMapping(null, null);\n\n const segment = segments[index];\n return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);\n }\n }\n}\n\nfunction clone(\n map: TraceMap | DecodedSourceMap | EncodedSourceMap,\n mappings: T,\n): T extends string ? EncodedSourceMap : DecodedSourceMap {\n return {\n version: map.version,\n file: map.file,\n names: map.names,\n sourceRoot: map.sourceRoot,\n sources: map.sources,\n sourcesContent: map.sourcesContent,\n mappings,\n } as any;\n}\n\nfunction OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;\nfunction OMapping(\n source: string,\n line: number,\n column: number,\n name: string | null,\n): OriginalMapping;\nfunction OMapping(\n source: string | null,\n line: number | null,\n column: number | null,\n name: string | null,\n): OriginalMapping | InvalidOriginalMapping {\n return { source, line, column, name } as any;\n}\n\nfunction GMapping(line: null, column: null): InvalidGeneratedMapping;\nfunction GMapping(line: number, column: number): GeneratedMapping;\nfunction GMapping(\n line: number | null,\n column: number | null,\n): GeneratedMapping | InvalidGeneratedMapping {\n return { line, column } as any;\n}\n\nfunction traceSegmentInternal(\n segments: SourceMapSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number;\nfunction traceSegmentInternal(\n segments: SourceMapSegment[] | ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): number {\n let index = memoizedBinarySearch(segments, column, memo, line);\n if (bsFound) {\n index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);\n } else if (bias === LEAST_UPPER_BOUND) index++;\n\n if (index === -1 || index === segments.length) return -1;\n return index;\n}\n\nfunction sliceGeneratedPositions(\n segments: ReverseSegment[],\n memo: MemoState,\n line: number,\n column: number,\n bias: Bias,\n): GeneratedMapping[] {\n let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);\n\n // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in\n // insertion order) segment that matched. Even if we did respect the bias when tracing, we would\n // still need to call `lowerBound()` to find the first segment, which is slower than just looking\n // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the\n // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to\n // match LEAST_UPPER_BOUND.\n if (!bsFound && bias === LEAST_UPPER_BOUND) min++;\n\n if (min === -1 || min === segments.length) return [];\n\n // We may have found the segment that started at an earlier column. If this is the case, then we\n // need to slice all generated segments that match _that_ column, because all such segments span\n // to our desired column.\n const matchedColumn = bsFound ? column : segments[min][COLUMN];\n\n // The binary search is not guaranteed to find the lower bound when a match wasn't found.\n if (!bsFound) min = lowerBound(segments, matchedColumn, min);\n const max = upperBound(segments, matchedColumn, min);\n\n const result = [];\n for (; min <= max; min++) {\n const segment = segments[min];\n result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));\n }\n return result;\n}\n"],"names":["resolveUri","presortedDecodedMap","decodedMappings","encodedMappings","traceSegment","originalPositionFor","generatedP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AC,CAAC;IACvF,KAAA;IACD,IAAA,OAAO,MAAM,CAAC;IAChB;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts new file mode 100644 index 0000000..08bca6b --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/any-map.d.ts @@ -0,0 +1,8 @@ +import { TraceMap } from './trace-mapping'; +import type { SectionedSourceMapInput } from './types'; +declare type AnyMap = { + new (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; + (map: SectionedSourceMapInput, mapUrl?: string | null): TraceMap; +}; +export declare const AnyMap: AnyMap; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts new file mode 100644 index 0000000..88820e5 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/binary-search.d.ts @@ -0,0 +1,32 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +export declare type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts new file mode 100644 index 0000000..8d1e538 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/by-source.d.ts @@ -0,0 +1,7 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; +import type { MemoState } from './binary-search'; +export declare type Source = { + __proto__: null; + [line: number]: Exclude[]; +}; +export default function buildBySources(decoded: readonly SourceMapSegment[][], memos: MemoState[]): Source[]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts new file mode 100644 index 0000000..cf7d4f8 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/resolve.d.ts @@ -0,0 +1 @@ +export default function resolve(input: string, base: string | undefined): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts new file mode 100644 index 0000000..2bfb5dc --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sort.d.ts @@ -0,0 +1,2 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export default function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..6d70924 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,16 @@ +declare type GeneratedColumn = number; +declare type SourcesIndex = number; +declare type SourceLine = number; +declare type SourceColumn = number; +declare type NamesIndex = number; +declare type GeneratedLine = number; +export declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts new file mode 100644 index 0000000..bead5c1 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/strip-filename.d.ts @@ -0,0 +1,4 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string; diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts new file mode 100644 index 0000000..c125ead --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/trace-mapping.d.ts @@ -0,0 +1,74 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping } from './types'; +export type { SourceMapSegment } from './sourcemap-segment'; +export type { SourceMapInput, SectionedSourceMapInput, DecodedSourceMap, EncodedSourceMap, SectionedSourceMap, InvalidOriginalMapping, OriginalMapping as Mapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, EachMapping, } from './types'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare let encodedMappings: (map: TraceMap) => EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare let decodedMappings: (map: TraceMap) => Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare let traceSegment: (map: TraceMap, line: number, column: number) => Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare let originalPositionFor: (map: TraceMap, needle: Needle) => OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export declare let generatedPositionFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping | InvalidGeneratedMapping; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export declare let allGeneratedPositionsFor: (map: TraceMap, needle: SourceNeedle) => GeneratedMapping[]; +/** + * Iterates each mapping in generated position order. + */ +export declare let eachMapping: (map: TraceMap, cb: (mapping: EachMapping) => void) => void; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export declare let sourceContentFor: (map: TraceMap, source: string) => string | null; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare let presortedDecodedMap: (map: DecodedSourceMap, mapUrl?: string) => TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let decodedMap: (map: TraceMap) => Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare let encodedMap: (map: TraceMap) => EncodedSourceMap; +export { AnyMap } from './any-map'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: SourceMapInput, mapUrl?: string | null); +} diff --git a/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..2f4fd45 --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/dist/types/types.d.ts @@ -0,0 +1,92 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export declare type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export declare type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export declare type GeneratedMapping = { + line: number; + column: number; +}; +export declare type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export declare type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +export declare type SourceMapInput = string | Ro | Ro | TraceMap; +export declare type SectionedSourceMapInput = SourceMapInput | Ro; +export declare type Needle = { + line: number; + column: number; + bias?: Bias; +}; +export declare type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +export declare type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; +} +export declare type Ro = T extends Array ? V[] | Readonly | RoArray | Readonly> : T extends object ? T | Readonly | RoObject | Readonly> : T; +declare type RoArray = Ro[]; +declare type RoObject = { + [K in keyof T]: T[K] | Ro; +}; +export {}; diff --git a/node_modules/@jridgewell/trace-mapping/package.json b/node_modules/@jridgewell/trace-mapping/package.json new file mode 100644 index 0000000..db3f8ac --- /dev/null +++ b/node_modules/@jridgewell/trace-mapping/package.json @@ -0,0 +1,75 @@ +{ + "name": "@jridgewell/trace-mapping", + "version": "0.3.17", + "description": "Trace the original position through a source map", + "keywords": [ + "source", + "map" + ], + "main": "dist/trace-mapping.umd.js", + "module": "dist/trace-mapping.mjs", + "typings": "dist/types/trace-mapping.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": [ + { + "types": "./dist/types/trace-mapping.d.ts", + "browser": "./dist/trace-mapping.umd.js", + "require": "./dist/trace-mapping.umd.js", + "import": "./dist/trace-mapping.mjs" + }, + "./dist/trace-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "author": "Justin Ridgewell ", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/trace-mapping.git" + }, + "license": "MIT", + "scripts": { + "benchmark": "run-s build:rollup benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.mjs", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "prebuild": "rm -rf dist", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build", + "test": "run-s -n test:lint test:only", + "test:debug": "ava debug", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts' '**/*.md'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "c8 ava", + "test:watch": "ava --watch" + }, + "devDependencies": { + "@rollup/plugin-typescript": "8.5.0", + "@typescript-eslint/eslint-plugin": "5.39.0", + "@typescript-eslint/parser": "5.39.0", + "ava": "4.3.3", + "benchmark": "2.1.4", + "c8": "7.12.0", + "esbuild": "0.15.10", + "eslint": "8.25.0", + "eslint-config-prettier": "8.5.0", + "eslint-plugin-no-only-tests": "3.0.0", + "npm-run-all": "4.1.5", + "prettier": "2.7.1", + "rollup": "2.79.1", + "tsx": "3.10.1", + "typescript": "4.8.4" + }, + "dependencies": { + "@jridgewell/resolve-uri": "3.1.0", + "@jridgewell/sourcemap-codec": "1.4.14" + } +} diff --git a/node_modules/@sinclair/typebox/compiler/compiler.d.ts b/node_modules/@sinclair/typebox/compiler/compiler.d.ts new file mode 100644 index 0000000..bcdb587 --- /dev/null +++ b/node_modules/@sinclair/typebox/compiler/compiler.d.ts @@ -0,0 +1,28 @@ +import { ValueError } from '../errors/index'; +import * as Types from '../typebox'; +export declare type CheckFunction = (value: unknown) => boolean; +export declare class TypeCheck { + private readonly schema; + private readonly references; + private readonly checkFunc; + private readonly code; + constructor(schema: T, references: Types.TSchema[], checkFunc: CheckFunction, code: string); + /** Returns the generated validation code used to validate this type. */ + Code(): string; + /** Returns an iterator for each error in this value. */ + Errors(value: unknown): IterableIterator; + /** Returns true if the value matches the given type. */ + Check(value: unknown): value is Types.Static; +} +export declare namespace Property { + function Check(propertyName: string): boolean; +} +export declare class TypeCompilerUnknownTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +/** Compiles Types for Runtime Type Checking */ +export declare namespace TypeCompiler { + /** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */ + function Compile(schema: T, references?: Types.TSchema[]): TypeCheck; +} diff --git a/node_modules/@sinclair/typebox/compiler/compiler.js b/node_modules/@sinclair/typebox/compiler/compiler.js new file mode 100644 index 0000000..1f9496d --- /dev/null +++ b/node_modules/@sinclair/typebox/compiler/compiler.js @@ -0,0 +1,409 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/compiler + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.TypeCompiler = exports.TypeCompilerUnknownTypeError = exports.Property = exports.TypeCheck = void 0; +const index_1 = require("../errors/index"); +const index_2 = require("../guard/index"); +const index_3 = require("../format/index"); +const Types = require("../typebox"); +// ------------------------------------------------------------------- +// TypeCheck +// ------------------------------------------------------------------- +class TypeCheck { + constructor(schema, references, checkFunc, code) { + this.schema = schema; + this.references = references; + this.checkFunc = checkFunc; + this.code = code; + } + /** Returns the generated validation code used to validate this type. */ + Code() { + return this.code; + } + /** Returns an iterator for each error in this value. */ + Errors(value) { + return index_1.ValueErrors.Errors(this.schema, this.references, value); + } + /** Returns true if the value matches the given type. */ + Check(value) { + return this.checkFunc(value); + } +} +exports.TypeCheck = TypeCheck; +// ------------------------------------------------------------------- +// Property +// ------------------------------------------------------------------- +var Property; +(function (Property) { + function DollarSign(code) { + return code === 36; + } + function Underscore(code) { + return code === 95; + } + function Numeric(code) { + return code >= 48 && code <= 57; + } + function Alpha(code) { + return (code >= 65 && code <= 90) || (code >= 97 && code <= 122); + } + function Check(propertyName) { + if (propertyName.length === 0) + return false; + { + const code = propertyName.charCodeAt(0); + if (!(DollarSign(code) || Underscore(code) || Alpha(code))) { + return false; + } + } + for (let i = 1; i < propertyName.length; i++) { + const code = propertyName.charCodeAt(i); + if (!(DollarSign(code) || Underscore(code) || Alpha(code) || Numeric(code))) { + return false; + } + } + return true; + } + Property.Check = Check; +})(Property = exports.Property || (exports.Property = {})); +// ------------------------------------------------------------------- +// TypeCompiler +// ------------------------------------------------------------------- +class TypeCompilerUnknownTypeError extends Error { + constructor(schema) { + super('TypeCompiler: Unknown type'); + this.schema = schema; + } +} +exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError; +/** Compiles Types for Runtime Type Checking */ +var TypeCompiler; +(function (TypeCompiler) { + // ------------------------------------------------------------------- + // Types + // ------------------------------------------------------------------- + function* Any(schema, value) { + yield '(true)'; + } + function* Array(schema, value) { + const expression = CreateExpression(schema.items, 'value'); + if (schema.minItems !== undefined) + yield `(${value}.length >= ${schema.minItems})`; + if (schema.maxItems !== undefined) + yield `(${value}.length <= ${schema.maxItems})`; + if (schema.uniqueItems !== undefined) + yield `(new Set(${value}).size === ${value}.length)`; + yield `(Array.isArray(${value}) && ${value}.every(value => ${expression}))`; + } + function* Boolean(schema, value) { + yield `(typeof ${value} === 'boolean')`; + } + function* Constructor(schema, value) { + yield* Visit(schema.returns, `${value}.prototype`); + } + function* Function(schema, value) { + yield `(typeof ${value} === 'function')`; + } + function* Integer(schema, value) { + yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`; + if (schema.multipleOf !== undefined) + yield `(${value} % ${schema.multipleOf} === 0)`; + if (schema.exclusiveMinimum !== undefined) + yield `(${value} > ${schema.exclusiveMinimum})`; + if (schema.exclusiveMaximum !== undefined) + yield `(${value} < ${schema.exclusiveMaximum})`; + if (schema.minimum !== undefined) + yield `(${value} >= ${schema.minimum})`; + if (schema.maximum !== undefined) + yield `(${value} <= ${schema.maximum})`; + } + function* Literal(schema, value) { + if (typeof schema.const === 'number' || typeof schema.const === 'boolean') { + yield `(${value} === ${schema.const})`; + } + else { + yield `(${value} === '${schema.const}')`; + } + } + function* Never(schema, value) { + yield `(false)`; + } + function* Null(schema, value) { + yield `(${value} === null)`; + } + function* Number(schema, value) { + yield `(typeof ${value} === 'number')`; + if (schema.multipleOf !== undefined) + yield `(${value} % ${schema.multipleOf} === 0)`; + if (schema.exclusiveMinimum !== undefined) + yield `(${value} > ${schema.exclusiveMinimum})`; + if (schema.exclusiveMaximum !== undefined) + yield `(${value} < ${schema.exclusiveMaximum})`; + if (schema.minimum !== undefined) + yield `(${value} >= ${schema.minimum})`; + if (schema.maximum !== undefined) + yield `(${value} <= ${schema.maximum})`; + } + function* Object(schema, value) { + yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`; + if (schema.minProperties !== undefined) + yield `(Object.keys(${value}).length >= ${schema.minProperties})`; + if (schema.maxProperties !== undefined) + yield `(Object.keys(${value}).length <= ${schema.maxProperties})`; + const propertyKeys = globalThis.Object.keys(schema.properties); + if (schema.additionalProperties === false) { + // Optimization: If the property key length matches the required keys length + // then we only need check that the values property key length matches that + // of the property key length. This is because exhaustive testing for values + // will occur in subsequent property tests. + if (schema.required && schema.required.length === propertyKeys.length) { + yield `(Object.keys(${value}).length === ${propertyKeys.length})`; + } + else { + const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`; + yield `(Object.keys(${value}).every(key => ${keys}.includes(key)))`; + } + } + if (index_2.TypeGuard.TSchema(schema.additionalProperties)) { + const expression = CreateExpression(schema.additionalProperties, 'value[key]'); + const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`; + yield `(Object.keys(${value}).every(key => ${keys}.includes(key) || ${expression}))`; + } + for (const propertyKey of propertyKeys) { + const memberExpression = Property.Check(propertyKey) ? `${value}.${propertyKey}` : `${value}['${propertyKey}']`; + const propertySchema = schema.properties[propertyKey]; + if (schema.required && schema.required.includes(propertyKey)) { + yield* Visit(propertySchema, memberExpression); + } + else { + const expression = CreateExpression(propertySchema, memberExpression); + yield `(${memberExpression} === undefined ? true : (${expression}))`; + } + } + } + function* Promise(schema, value) { + yield `(typeof value === 'object' && typeof ${value}.then === 'function')`; + } + function* Record(schema, value) { + yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`; + const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; + const local = PushLocal(`new RegExp(/${keyPattern}/)`); + yield `(Object.keys(${value}).every(key => ${local}.test(key)))`; + const expression = CreateExpression(valueSchema, 'value'); + yield `(Object.values(${value}).every(value => ${expression}))`; + } + function* Ref(schema, value) { + // Reference: If we have seen this reference before we can just yield and return + // the function call. If this isn't the case we defer to visit to generate and + // set the function for subsequent passes. Consider for refactor. + if (names.has(schema.$ref)) + return yield `(${CreateFunctionName(schema.$ref)}(${value}))`; + if (!referenceMap.has(schema.$ref)) + throw Error(`TypeCompiler.Ref: Cannot de-reference schema with $id '${schema.$ref}'`); + const reference = referenceMap.get(schema.$ref); + yield* Visit(reference, value); + } + function* Self(schema, value) { + const func = CreateFunctionName(schema.$ref); + yield `(${func}(${value}))`; + } + function* String(schema, value) { + yield `(typeof ${value} === 'string')`; + if (schema.minLength !== undefined) { + yield `(${value}.length >= ${schema.minLength})`; + } + if (schema.maxLength !== undefined) { + yield `(${value}.length <= ${schema.maxLength})`; + } + if (schema.pattern !== undefined) { + const local = PushLocal(`new RegExp(/${schema.pattern}/);`); + yield `(${local}.test(${value}))`; + } + if (schema.format !== undefined) { + yield `(format('${schema.format}', ${value}))`; + } + } + function* Tuple(schema, value) { + yield `(Array.isArray(${value}))`; + if (schema.items === undefined) + return yield `(${value}.length === 0)`; + yield `(${value}.length === ${schema.maxItems})`; + for (let i = 0; i < schema.items.length; i++) { + const expression = CreateExpression(schema.items[i], `${value}[${i}]`); + yield `(${expression})`; + } + } + function* Undefined(schema, value) { + yield `(${value} === undefined)`; + } + function* Union(schema, value) { + const expressions = schema.anyOf.map((schema) => CreateExpression(schema, value)); + yield `(${expressions.join(' || ')})`; + } + function* Uint8Array(schema, value) { + yield `(${value} instanceof Uint8Array)`; + if (schema.maxByteLength) + yield `(${value}.length <= ${schema.maxByteLength})`; + if (schema.minByteLength) + yield `(${value}.length >= ${schema.minByteLength})`; + } + function* Unknown(schema, value) { + yield '(true)'; + } + function* Void(schema, value) { + yield `(${value} === null)`; + } + function* Visit(schema, value) { + // Reference: Referenced schemas can originate from either additional schemas + // or inline in the schema itself. Ideally the recursive path should align to + // reference path. Consider for refactor. + if (schema.$id && !names.has(schema.$id)) { + names.add(schema.$id); + const name = CreateFunctionName(schema.$id); + const body = CreateFunction(name, schema, 'value'); + PushFunction(body); + yield `(${name}(${value}))`; + return; + } + const anySchema = schema; + switch (anySchema[Types.Kind]) { + case 'Any': + return yield* Any(anySchema, value); + case 'Array': + return yield* Array(anySchema, value); + case 'Boolean': + return yield* Boolean(anySchema, value); + case 'Constructor': + return yield* Constructor(anySchema, value); + case 'Function': + return yield* Function(anySchema, value); + case 'Integer': + return yield* Integer(anySchema, value); + case 'Literal': + return yield* Literal(anySchema, value); + case 'Never': + return yield* Never(anySchema, value); + case 'Null': + return yield* Null(anySchema, value); + case 'Number': + return yield* Number(anySchema, value); + case 'Object': + return yield* Object(anySchema, value); + case 'Promise': + return yield* Promise(anySchema, value); + case 'Record': + return yield* Record(anySchema, value); + case 'Ref': + return yield* Ref(anySchema, value); + case 'Self': + return yield* Self(anySchema, value); + case 'String': + return yield* String(anySchema, value); + case 'Tuple': + return yield* Tuple(anySchema, value); + case 'Undefined': + return yield* Undefined(anySchema, value); + case 'Union': + return yield* Union(anySchema, value); + case 'Uint8Array': + return yield* Uint8Array(anySchema, value); + case 'Unknown': + return yield* Unknown(anySchema, value); + case 'Void': + return yield* Void(anySchema, value); + default: + throw new TypeCompilerUnknownTypeError(schema); + } + } + // ------------------------------------------------------------------- + // Compile State + // ------------------------------------------------------------------- + const referenceMap = new Map(); + const locals = new Set(); // local variables and functions + const names = new Set(); // cache of local functions + function ResetCompiler() { + referenceMap.clear(); + locals.clear(); + names.clear(); + } + function AddReferences(schemas = []) { + for (const schema of schemas) { + if (!schema.$id) + throw new Error(`TypeCompiler: Referenced schemas must specify an $id.`); + if (referenceMap.has(schema.$id)) + throw new Error(`TypeCompiler: Duplicate schema $id found for '${schema.$id}'`); + referenceMap.set(schema.$id, schema); + } + } + function CreateExpression(schema, value) { + return [...Visit(schema, value)].join(' && '); + } + function CreateFunctionName($id) { + return `check_${$id.replace(/-/g, '_')}`; + } + function CreateFunction(name, schema, value) { + const expression = [...Visit(schema, value)].map((condition) => ` ${condition}`).join(' &&\n'); + return `function ${name}(value) {\n return (\n${expression}\n )\n}`; + } + function PushFunction(functionBody) { + locals.add(functionBody); + } + function PushLocal(expression) { + const local = `local_${locals.size}`; + locals.add(`const ${local} = ${expression}`); + return local; + } + function GetLocals() { + return [...locals.values()]; + } + // ------------------------------------------------------------------- + // Compile + // ------------------------------------------------------------------- + function Build(schema, references = []) { + ResetCompiler(); + AddReferences(references); + const check = CreateFunction('check', schema, 'value'); + const locals = GetLocals(); + return `${locals.join('\n')}\nreturn ${check}`; + } + /** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */ + function Compile(schema, references = []) { + index_2.TypeGuard.Assert(schema, references); + const code = Build(schema, references); + const func1 = globalThis.Function('format', code); + const func2 = func1((format, value) => { + if (!index_3.Format.Has(format)) + return false; + const func = index_3.Format.Get(format); + return func(value); + }); + return new TypeCheck(schema, references, func2, code); + } + TypeCompiler.Compile = Compile; +})(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {})); diff --git a/node_modules/@sinclair/typebox/compiler/index.d.ts b/node_modules/@sinclair/typebox/compiler/index.d.ts new file mode 100644 index 0000000..4062a62 --- /dev/null +++ b/node_modules/@sinclair/typebox/compiler/index.d.ts @@ -0,0 +1,2 @@ +export { ValueError, ValueErrorType } from '../errors/index'; +export * from './compiler'; diff --git a/node_modules/@sinclair/typebox/compiler/index.js b/node_modules/@sinclair/typebox/compiler/index.js new file mode 100644 index 0000000..deeb16f --- /dev/null +++ b/node_modules/@sinclair/typebox/compiler/index.js @@ -0,0 +1,47 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/compiler + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueErrorType = void 0; +var index_1 = require("../errors/index"); +Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } }); +__exportStar(require("./compiler"), exports); diff --git a/node_modules/@sinclair/typebox/conditional/conditional.d.ts b/node_modules/@sinclair/typebox/conditional/conditional.d.ts new file mode 100644 index 0000000..d078ca0 --- /dev/null +++ b/node_modules/@sinclair/typebox/conditional/conditional.d.ts @@ -0,0 +1,17 @@ +import * as Types from '../typebox'; +export declare type TExtends = Types.Static extends Types.Static ? T : U; +export interface TExclude extends Types.TUnion { + static: Exclude, Types.Static>; +} +export interface TExtract extends Types.TUnion { + static: Extract, Types.Static>; +} +/** Conditional Types */ +export declare namespace Conditional { + /** (Experimental) Creates a conditional expression type */ + function Extends(left: L, right: R, ok: T, fail: U): TExtends; + /** (Experimental) Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers. */ + function Exclude(unionType: T, excludedMembers: U, options?: Types.SchemaOptions): TExclude; + /** (Experimental) Constructs a type by extracting from Type all union members that are assignable to Union. */ + function Extract(type: T, union: U, options?: Types.SchemaOptions): TExtract; +} diff --git a/node_modules/@sinclair/typebox/conditional/conditional.js b/node_modules/@sinclair/typebox/conditional/conditional.js new file mode 100644 index 0000000..59d297c --- /dev/null +++ b/node_modules/@sinclair/typebox/conditional/conditional.js @@ -0,0 +1,91 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/conditional + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.Conditional = void 0; +const Types = require("../typebox"); +const structural_1 = require("./structural"); +const index_1 = require("../guard/index"); +/** Conditional Types */ +var Conditional; +(function (Conditional) { + /** (Experimental) Creates a conditional expression type */ + function Extends(left, right, ok, fail) { + switch (structural_1.Structural.Check(left, right)) { + case structural_1.StructuralResult.Union: + return Types.Type.Union([Clone(ok), Clone(fail)]); + case structural_1.StructuralResult.True: + return Clone(ok); + case structural_1.StructuralResult.False: + return Clone(fail); + } + } + Conditional.Extends = Extends; + /** (Experimental) Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers. */ + function Exclude(unionType, excludedMembers, options = {}) { + const anyOf = unionType.anyOf + .filter((schema) => { + const check = structural_1.Structural.Check(schema, excludedMembers); + return !(check === structural_1.StructuralResult.True || check === structural_1.StructuralResult.Union); + }) + .map((schema) => Clone(schema)); + return { ...options, [Types.Kind]: 'Union', anyOf }; + } + Conditional.Exclude = Exclude; + /** (Experimental) Constructs a type by extracting from Type all union members that are assignable to Union. */ + function Extract(type, union, options = {}) { + if (index_1.TypeGuard.TUnion(type)) { + const anyOf = type.anyOf.filter((schema) => structural_1.Structural.Check(schema, union) === structural_1.StructuralResult.True).map((schema) => Clone(schema)); + return { ...options, [Types.Kind]: 'Union', anyOf }; + } + else { + const anyOf = union.anyOf.filter((schema) => structural_1.Structural.Check(type, schema) === structural_1.StructuralResult.True).map((schema) => Clone(schema)); + return { ...options, [Types.Kind]: 'Union', anyOf }; + } + } + Conditional.Extract = Extract; + function Clone(value) { + const isObject = (object) => typeof object === 'object' && object !== null && !Array.isArray(object); + const isArray = (object) => typeof object === 'object' && object !== null && Array.isArray(object); + if (isObject(value)) { + return Object.keys(value).reduce((acc, key) => ({ + ...acc, + [key]: Clone(value[key]), + }), Object.getOwnPropertySymbols(value).reduce((acc, key) => ({ + ...acc, + [key]: Clone(value[key]), + }), {})); + } + else if (isArray(value)) { + return value.map((item) => Clone(item)); + } + else { + return value; + } + } +})(Conditional = exports.Conditional || (exports.Conditional = {})); diff --git a/node_modules/@sinclair/typebox/conditional/index.d.ts b/node_modules/@sinclair/typebox/conditional/index.d.ts new file mode 100644 index 0000000..773425d --- /dev/null +++ b/node_modules/@sinclair/typebox/conditional/index.d.ts @@ -0,0 +1,2 @@ +export * from './conditional'; +export * from './structural'; diff --git a/node_modules/@sinclair/typebox/conditional/index.js b/node_modules/@sinclair/typebox/conditional/index.js new file mode 100644 index 0000000..621910b --- /dev/null +++ b/node_modules/@sinclair/typebox/conditional/index.js @@ -0,0 +1,45 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/conditional + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./conditional"), exports); +__exportStar(require("./structural"), exports); diff --git a/node_modules/@sinclair/typebox/conditional/structural.d.ts b/node_modules/@sinclair/typebox/conditional/structural.d.ts new file mode 100644 index 0000000..7ba8fc7 --- /dev/null +++ b/node_modules/@sinclair/typebox/conditional/structural.d.ts @@ -0,0 +1,11 @@ +import * as Types from '../typebox'; +export declare enum StructuralResult { + Union = 0, + True = 1, + False = 2 +} +/** Performs structural equivalence checks against TypeBox types. */ +export declare namespace Structural { + /** Structurally tests if the left schema extends the right. */ + function Check(left: Types.TSchema, right: Types.TSchema): StructuralResult; +} diff --git a/node_modules/@sinclair/typebox/conditional/structural.js b/node_modules/@sinclair/typebox/conditional/structural.js new file mode 100644 index 0000000..cdd4ba0 --- /dev/null +++ b/node_modules/@sinclair/typebox/conditional/structural.js @@ -0,0 +1,657 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/conditional + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.Structural = exports.StructuralResult = void 0; +const Types = require("../typebox"); +const guard_1 = require("../guard"); +// -------------------------------------------------------------------------- +// StructuralResult +// -------------------------------------------------------------------------- +var StructuralResult; +(function (StructuralResult) { + StructuralResult[StructuralResult["Union"] = 0] = "Union"; + StructuralResult[StructuralResult["True"] = 1] = "True"; + StructuralResult[StructuralResult["False"] = 2] = "False"; +})(StructuralResult = exports.StructuralResult || (exports.StructuralResult = {})); +// -------------------------------------------------------------------------- +// Structural +// -------------------------------------------------------------------------- +/** Performs structural equivalence checks against TypeBox types. */ +var Structural; +(function (Structural) { + const referenceMap = new Map(); + // ------------------------------------------------------------------------ + // Rules + // ------------------------------------------------------------------------ + function AnyOrUnknownRule(right) { + // https://github.com/microsoft/TypeScript/issues/40049 + if (right[Types.Kind] === 'Union' && right.anyOf.some((schema) => schema[Types.Kind] === 'Any' || schema[Types.Kind] === 'Unknown')) + return true; + if (right[Types.Kind] === 'Unknown') + return true; + if (right[Types.Kind] === 'Any') + return true; + return false; + } + function ObjectRightRule(left, right) { + // type A = boolean extends {} ? 1 : 2 // additionalProperties: false + // type B = boolean extends object ? 1 : 2 // additionalProperties: true + const additionalProperties = right.additionalProperties; + const propertyLength = globalThis.Object.keys(right.properties).length; + return additionalProperties === false && propertyLength === 0; + } + function UnionRightRule(left, right) { + const result = right.anyOf.some((right) => Visit(left, right) !== StructuralResult.False); + return result ? StructuralResult.True : StructuralResult.False; + } + // ------------------------------------------------------------------------ + // Records + // ------------------------------------------------------------------------ + function RecordPattern(schema) { + return globalThis.Object.keys(schema.patternProperties)[0]; + } + function RecordNumberOrStringKey(schema) { + const pattern = RecordPattern(schema); + return pattern === '^.*$' || pattern === '^(0|[1-9][0-9]*)$'; + } + function RecordValue(schema) { + const pattern = RecordPattern(schema); + return schema.patternProperties[pattern]; + } + function RecordKey(schema) { + const pattern = RecordPattern(schema); + if (pattern === '^.*$') { + return Types.Type.String(); + } + else if (pattern === '^(0|[1-9][0-9]*)$') { + return Types.Type.Number(); + } + else { + const keys = pattern.slice(1, pattern.length - 1).split('|'); + const schemas = keys.map((key) => (isNaN(+key) ? Types.Type.Literal(key) : Types.Type.Literal(parseFloat(key)))); + return Types.Type.Union(schemas); + } + } + function PropertyMap(schema) { + const comparable = new Map(); + if (guard_1.TypeGuard.TRecord(schema)) { + const propertyPattern = RecordPattern(schema); + if (propertyPattern === '^.*$' || propertyPattern === '^(0|[1-9][0-9]*)$') + throw Error('Cannot extract record properties without property constraints'); + const propertySchema = schema.patternProperties[propertyPattern]; + const propertyKeys = propertyPattern.slice(1, propertyPattern.length - 1).split('|'); + propertyKeys.forEach((propertyKey) => { + comparable.set(propertyKey, propertySchema); + }); + } + else { + globalThis.Object.entries(schema.properties).forEach(([propertyKey, propertySchema]) => { + comparable.set(propertyKey, propertySchema); + }); + } + return comparable; + } + // ------------------------------------------------------------------------ + // Indexable + // ------------------------------------------------------------------------ + function Indexable(left, right) { + if (guard_1.TypeGuard.TUnion(right)) { + return StructuralResult.False; + } + else { + return Visit(left, right); + } + } + // ------------------------------------------------------------------------ + // Checks + // ------------------------------------------------------------------------ + function Any(left, right) { + return AnyOrUnknownRule(right) ? StructuralResult.True : StructuralResult.Union; + } + function Array(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right)) { + if (right.properties['length'] !== undefined && right.properties['length'][Types.Kind] === 'Number') + return StructuralResult.True; + if (globalThis.Object.keys(right.properties).length === 0) + return StructuralResult.True; + return StructuralResult.False; + } + else if (!guard_1.TypeGuard.TArray(right)) { + return StructuralResult.False; + } + else if (left.items === undefined && right.items !== undefined) { + return StructuralResult.False; + } + else if (left.items !== undefined && right.items === undefined) { + return StructuralResult.False; + } + else if (left.items === undefined && right.items === undefined) { + return StructuralResult.False; + } + else { + const result = Visit(left.items, right.items) !== StructuralResult.False; + return result ? StructuralResult.True : StructuralResult.False; + } + } + function Boolean(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right) && ObjectRightRule(left, right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TBoolean(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TUnion(right)) { + return UnionRightRule(left, right); + } + else { + return StructuralResult.False; + } + } + function Constructor(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right) && globalThis.Object.keys(right.properties).length === 0) { + return StructuralResult.True; + } + else if (!guard_1.TypeGuard.TConstructor(right)) { + return StructuralResult.False; + } + else if (right.parameters.length < left.parameters.length) { + return StructuralResult.False; + } + else { + if (Visit(left.returns, right.returns) === StructuralResult.False) { + return StructuralResult.False; + } + for (let i = 0; i < left.parameters.length; i++) { + const result = Visit(right.parameters[i], left.parameters[i]); + if (result === StructuralResult.False) + return StructuralResult.False; + } + return StructuralResult.True; + } + } + function Function(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right)) { + if (right.properties['length'] !== undefined && right.properties['length'][Types.Kind] === 'Number') + return StructuralResult.True; + if (globalThis.Object.keys(right.properties).length === 0) + return StructuralResult.True; + return StructuralResult.False; + } + else if (!guard_1.TypeGuard.TFunction(right)) { + return StructuralResult.False; + } + else if (right.parameters.length < left.parameters.length) { + return StructuralResult.False; + } + else if (Visit(left.returns, right.returns) === StructuralResult.False) { + return StructuralResult.False; + } + else { + for (let i = 0; i < left.parameters.length; i++) { + const result = Visit(right.parameters[i], left.parameters[i]); + if (result === StructuralResult.False) + return StructuralResult.False; + } + return StructuralResult.True; + } + } + function Integer(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right) && ObjectRightRule(left, right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TInteger(right) || guard_1.TypeGuard.TNumber(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TUnion(right)) { + return UnionRightRule(left, right); + } + else { + return StructuralResult.False; + } + } + function Literal(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right) && ObjectRightRule(left, right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TRecord(right)) { + if (typeof left.const === 'string') { + return Indexable(left, RecordValue(right)); + } + else { + return StructuralResult.False; + } + } + else if (guard_1.TypeGuard.TLiteral(right) && left.const === right.const) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TString(right) && typeof left.const === 'string') { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TNumber(right) && typeof left.const === 'number') { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TInteger(right) && typeof left.const === 'number') { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TBoolean(right) && typeof left.const === 'boolean') { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TUnion(right)) { + return UnionRightRule(left, right); + } + else { + return StructuralResult.False; + } + } + function Number(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right) && ObjectRightRule(left, right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TNumber(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TInteger(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TUnion(right)) { + return UnionRightRule(left, right); + } + else { + return StructuralResult.False; + } + } + function Null(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TNull(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TUnion(right)) { + return UnionRightRule(left, right); + } + else { + return StructuralResult.False; + } + } + function Properties(left, right) { + if (right.size > left.size) + return StructuralResult.False; + if (![...right.keys()].every((rightKey) => left.has(rightKey))) + return StructuralResult.False; + for (const rightKey of right.keys()) { + const leftProp = left.get(rightKey); + const rightProp = right.get(rightKey); + if (Visit(leftProp, rightProp) === StructuralResult.False) { + return StructuralResult.False; + } + } + return StructuralResult.True; + } + function Object(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right)) { + return Properties(PropertyMap(left), PropertyMap(right)); + } + else if (guard_1.TypeGuard.TRecord(right)) { + if (!RecordNumberOrStringKey(right)) { + return Properties(PropertyMap(left), PropertyMap(right)); + } + else { + return StructuralResult.True; + } + } + else { + return StructuralResult.False; + } + } + function Promise(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right)) { + if (ObjectRightRule(left, right) || globalThis.Object.keys(right.properties).length === 0) { + return StructuralResult.True; + } + else { + return StructuralResult.False; + } + } + else if (!guard_1.TypeGuard.TPromise(right)) { + return StructuralResult.False; + } + else { + const result = Visit(left.item, right.item) !== StructuralResult.False; + return result ? StructuralResult.True : StructuralResult.False; + } + } + function Record(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right)) { + if (RecordPattern(left) === '^.*$' && right[Types.Hint] === 'Record') { + return StructuralResult.True; + } + else if (RecordPattern(left) === '^.*$') { + return StructuralResult.False; + } + else { + return globalThis.Object.keys(right.properties).length === 0 ? StructuralResult.True : StructuralResult.False; + } + } + else if (guard_1.TypeGuard.TRecord(right)) { + if (!RecordNumberOrStringKey(left) && !RecordNumberOrStringKey(right)) { + return Properties(PropertyMap(left), PropertyMap(right)); + } + else if (RecordNumberOrStringKey(left) && !RecordNumberOrStringKey(right)) { + const leftKey = RecordKey(left); + const rightKey = RecordKey(right); + if (Visit(rightKey, leftKey) === StructuralResult.False) { + return StructuralResult.False; + } + else { + return StructuralResult.True; + } + } + else { + return StructuralResult.True; + } + } + else { + return StructuralResult.False; + } + } + function Ref(left, right) { + if (!referenceMap.has(left.$ref)) + throw Error(`Cannot locate referenced $id '${left.$ref}'`); + const resolved = referenceMap.get(left.$ref); + return Visit(resolved, right); + } + function Self(left, right) { + if (!referenceMap.has(left.$ref)) + throw Error(`Cannot locate referenced self $id '${left.$ref}'`); + const resolved = referenceMap.get(left.$ref); + return Visit(resolved, right); + } + function String(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right) && ObjectRightRule(left, right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TRecord(right)) { + return Indexable(left, RecordValue(right)); + } + else if (guard_1.TypeGuard.TString(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TUnion(right)) { + return UnionRightRule(left, right); + } + else { + return StructuralResult.False; + } + } + function Tuple(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right)) { + const result = ObjectRightRule(left, right) || globalThis.Object.keys(right.properties).length === 0; + return result ? StructuralResult.True : StructuralResult.False; + } + else if (guard_1.TypeGuard.TRecord(right)) { + return Indexable(left, RecordValue(right)); + } + else if (guard_1.TypeGuard.TArray(right)) { + if (right.items === undefined) { + return StructuralResult.False; + } + else if (guard_1.TypeGuard.TUnion(right.items) && left.items) { + const result = left.items.every((left) => UnionRightRule(left, right.items) !== StructuralResult.False); + return result ? StructuralResult.True : StructuralResult.False; + } + else if (guard_1.TypeGuard.TAny(right.items)) { + return StructuralResult.True; + } + else { + return StructuralResult.False; + } + } + if (!guard_1.TypeGuard.TTuple(right)) + return StructuralResult.False; + if (left.items === undefined && right.items === undefined) + return StructuralResult.True; + if (left.items === undefined && right.items !== undefined) + return StructuralResult.False; + if (left.items !== undefined && right.items === undefined) + return StructuralResult.False; + if (left.items === undefined && right.items === undefined) + return StructuralResult.True; + if (left.minItems !== right.minItems || left.maxItems !== right.maxItems) + return StructuralResult.False; + for (let i = 0; i < left.items.length; i++) { + if (Visit(left.items[i], right.items[i]) === StructuralResult.False) + return StructuralResult.False; + } + return StructuralResult.True; + } + function Uint8Array(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TObject(right) && ObjectRightRule(left, right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TRecord(right)) { + return Indexable(left, RecordValue(right)); + } + else if (guard_1.TypeGuard.TUint8Array(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TUnion(right)) { + return UnionRightRule(left, right); + } + else { + return StructuralResult.False; + } + } + function Undefined(left, right) { + if (AnyOrUnknownRule(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TUndefined(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TVoid(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TUnion(right)) { + return UnionRightRule(left, right); + } + else { + return StructuralResult.False; + } + } + function Union(left, right) { + if (left.anyOf.some((left) => guard_1.TypeGuard.TAny(left))) { + return StructuralResult.Union; + } + else if (guard_1.TypeGuard.TUnion(right)) { + const result = left.anyOf.every((left) => right.anyOf.some((right) => Visit(left, right) !== StructuralResult.False)); + return result ? StructuralResult.True : StructuralResult.False; + } + else { + const result = left.anyOf.every((left) => Visit(left, right) !== StructuralResult.False); + return result ? StructuralResult.True : StructuralResult.False; + } + } + function Unknown(left, right) { + if (guard_1.TypeGuard.TUnion(right)) { + const result = right.anyOf.some((right) => guard_1.TypeGuard.TAny(right) || guard_1.TypeGuard.TUnknown(right)); + return result ? StructuralResult.True : StructuralResult.False; + } + else if (guard_1.TypeGuard.TAny(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TUnknown(right)) { + return StructuralResult.True; + } + else { + return StructuralResult.False; + } + } + function Void(left, right) { + if (guard_1.TypeGuard.TUnion(right)) { + const result = right.anyOf.some((right) => guard_1.TypeGuard.TAny(right) || guard_1.TypeGuard.TUnknown(right)); + return result ? StructuralResult.True : StructuralResult.False; + } + else if (guard_1.TypeGuard.TAny(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TUnknown(right)) { + return StructuralResult.True; + } + else if (guard_1.TypeGuard.TVoid(right)) { + return StructuralResult.True; + } + else { + return StructuralResult.False; + } + } + let recursionDepth = 0; + function Visit(left, right) { + recursionDepth += 1; + if (recursionDepth >= 1000) + return StructuralResult.True; + if (left.$id !== undefined) + referenceMap.set(left.$id, left); + if (right.$id !== undefined) + referenceMap.set(right.$id, right); + const resolvedRight = right[Types.Kind] === 'Self' ? referenceMap.get(right.$ref) : right; + if (guard_1.TypeGuard.TAny(left)) { + return Any(left, resolvedRight); + } + else if (guard_1.TypeGuard.TArray(left)) { + return Array(left, resolvedRight); + } + else if (guard_1.TypeGuard.TBoolean(left)) { + return Boolean(left, resolvedRight); + } + else if (guard_1.TypeGuard.TConstructor(left)) { + return Constructor(left, resolvedRight); + } + else if (guard_1.TypeGuard.TFunction(left)) { + return Function(left, resolvedRight); + } + else if (guard_1.TypeGuard.TInteger(left)) { + return Integer(left, resolvedRight); + } + else if (guard_1.TypeGuard.TLiteral(left)) { + return Literal(left, resolvedRight); + } + else if (guard_1.TypeGuard.TNull(left)) { + return Null(left, resolvedRight); + } + else if (guard_1.TypeGuard.TNumber(left)) { + return Number(left, resolvedRight); + } + else if (guard_1.TypeGuard.TObject(left)) { + return Object(left, resolvedRight); + } + else if (guard_1.TypeGuard.TPromise(left)) { + return Promise(left, resolvedRight); + } + else if (guard_1.TypeGuard.TRecord(left)) { + return Record(left, resolvedRight); + } + else if (guard_1.TypeGuard.TRef(left)) { + return Ref(left, resolvedRight); + } + else if (guard_1.TypeGuard.TSelf(left)) { + return Self(left, resolvedRight); + } + else if (guard_1.TypeGuard.TString(left)) { + return String(left, resolvedRight); + } + else if (guard_1.TypeGuard.TTuple(left)) { + return Tuple(left, resolvedRight); + } + else if (guard_1.TypeGuard.TUndefined(left)) { + return Undefined(left, resolvedRight); + } + else if (guard_1.TypeGuard.TUint8Array(left)) { + return Uint8Array(left, resolvedRight); + } + else if (guard_1.TypeGuard.TUnion(left)) { + return Union(left, resolvedRight); + } + else if (guard_1.TypeGuard.TUnknown(left)) { + return Unknown(left, resolvedRight); + } + else if (guard_1.TypeGuard.TVoid(left)) { + return Void(left, resolvedRight); + } + else { + throw Error(`Structural: Unknown left operand '${left[Types.Kind]}'`); + } + } + /** Structurally tests if the left schema extends the right. */ + function Check(left, right) { + referenceMap.clear(); + recursionDepth = 0; + return Visit(left, right); + } + Structural.Check = Check; +})(Structural = exports.Structural || (exports.Structural = {})); diff --git a/node_modules/@sinclair/typebox/errors/errors.d.ts b/node_modules/@sinclair/typebox/errors/errors.d.ts new file mode 100644 index 0000000..8c250d9 --- /dev/null +++ b/node_modules/@sinclair/typebox/errors/errors.d.ts @@ -0,0 +1,60 @@ +import * as Types from '../typebox'; +export declare enum ValueErrorType { + Array = 0, + ArrayMinItems = 1, + ArrayMaxItems = 2, + ArrayUniqueItems = 3, + Boolean = 4, + Function = 5, + Integer = 6, + IntegerMultipleOf = 7, + IntegerExclusiveMinimum = 8, + IntegerExclusiveMaximum = 9, + IntegerMinimum = 10, + IntegerMaximum = 11, + Literal = 12, + Never = 13, + Null = 14, + Number = 15, + NumberMultipleOf = 16, + NumberExclusiveMinimum = 17, + NumberExclusiveMaximum = 18, + NumberMinumum = 19, + NumberMaximum = 20, + Object = 21, + ObjectMinProperties = 22, + ObjectMaxProperties = 23, + ObjectAdditionalProperties = 24, + ObjectRequiredProperties = 25, + Promise = 26, + RecordKeyNumeric = 27, + RecordKeyString = 28, + String = 29, + StringMinLength = 30, + StringMaxLength = 31, + StringPattern = 32, + StringFormatUnknown = 33, + StringFormat = 34, + TupleZeroLength = 35, + TupleLength = 36, + Undefined = 37, + Union = 38, + Uint8Array = 39, + Uint8ArrayMinByteLength = 40, + Uint8ArrayMaxByteLength = 41, + Void = 42 +} +export interface ValueError { + type: ValueErrorType; + schema: Types.TSchema; + path: string; + value: unknown; + message: string; +} +export declare class ValueErrorsUnknownTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare namespace ValueErrors { + function Errors(schema: T, references: Types.TSchema[], value: any): IterableIterator; +} diff --git a/node_modules/@sinclair/typebox/errors/errors.js b/node_modules/@sinclair/typebox/errors/errors.js new file mode 100644 index 0000000..79344b6 --- /dev/null +++ b/node_modules/@sinclair/typebox/errors/errors.js @@ -0,0 +1,398 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/errors + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.ValueErrors = exports.ValueErrorsUnknownTypeError = exports.ValueErrorType = void 0; +const Types = require("../typebox"); +const index_1 = require("../format/index"); +// ------------------------------------------------------------------- +// ValueErrorType +// ------------------------------------------------------------------- +var ValueErrorType; +(function (ValueErrorType) { + ValueErrorType[ValueErrorType["Array"] = 0] = "Array"; + ValueErrorType[ValueErrorType["ArrayMinItems"] = 1] = "ArrayMinItems"; + ValueErrorType[ValueErrorType["ArrayMaxItems"] = 2] = "ArrayMaxItems"; + ValueErrorType[ValueErrorType["ArrayUniqueItems"] = 3] = "ArrayUniqueItems"; + ValueErrorType[ValueErrorType["Boolean"] = 4] = "Boolean"; + ValueErrorType[ValueErrorType["Function"] = 5] = "Function"; + ValueErrorType[ValueErrorType["Integer"] = 6] = "Integer"; + ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 7] = "IntegerMultipleOf"; + ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 8] = "IntegerExclusiveMinimum"; + ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 9] = "IntegerExclusiveMaximum"; + ValueErrorType[ValueErrorType["IntegerMinimum"] = 10] = "IntegerMinimum"; + ValueErrorType[ValueErrorType["IntegerMaximum"] = 11] = "IntegerMaximum"; + ValueErrorType[ValueErrorType["Literal"] = 12] = "Literal"; + ValueErrorType[ValueErrorType["Never"] = 13] = "Never"; + ValueErrorType[ValueErrorType["Null"] = 14] = "Null"; + ValueErrorType[ValueErrorType["Number"] = 15] = "Number"; + ValueErrorType[ValueErrorType["NumberMultipleOf"] = 16] = "NumberMultipleOf"; + ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 17] = "NumberExclusiveMinimum"; + ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 18] = "NumberExclusiveMaximum"; + ValueErrorType[ValueErrorType["NumberMinumum"] = 19] = "NumberMinumum"; + ValueErrorType[ValueErrorType["NumberMaximum"] = 20] = "NumberMaximum"; + ValueErrorType[ValueErrorType["Object"] = 21] = "Object"; + ValueErrorType[ValueErrorType["ObjectMinProperties"] = 22] = "ObjectMinProperties"; + ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 23] = "ObjectMaxProperties"; + ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 24] = "ObjectAdditionalProperties"; + ValueErrorType[ValueErrorType["ObjectRequiredProperties"] = 25] = "ObjectRequiredProperties"; + ValueErrorType[ValueErrorType["Promise"] = 26] = "Promise"; + ValueErrorType[ValueErrorType["RecordKeyNumeric"] = 27] = "RecordKeyNumeric"; + ValueErrorType[ValueErrorType["RecordKeyString"] = 28] = "RecordKeyString"; + ValueErrorType[ValueErrorType["String"] = 29] = "String"; + ValueErrorType[ValueErrorType["StringMinLength"] = 30] = "StringMinLength"; + ValueErrorType[ValueErrorType["StringMaxLength"] = 31] = "StringMaxLength"; + ValueErrorType[ValueErrorType["StringPattern"] = 32] = "StringPattern"; + ValueErrorType[ValueErrorType["StringFormatUnknown"] = 33] = "StringFormatUnknown"; + ValueErrorType[ValueErrorType["StringFormat"] = 34] = "StringFormat"; + ValueErrorType[ValueErrorType["TupleZeroLength"] = 35] = "TupleZeroLength"; + ValueErrorType[ValueErrorType["TupleLength"] = 36] = "TupleLength"; + ValueErrorType[ValueErrorType["Undefined"] = 37] = "Undefined"; + ValueErrorType[ValueErrorType["Union"] = 38] = "Union"; + ValueErrorType[ValueErrorType["Uint8Array"] = 39] = "Uint8Array"; + ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 40] = "Uint8ArrayMinByteLength"; + ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 41] = "Uint8ArrayMaxByteLength"; + ValueErrorType[ValueErrorType["Void"] = 42] = "Void"; +})(ValueErrorType = exports.ValueErrorType || (exports.ValueErrorType = {})); +// ------------------------------------------------------------------- +// ValueErrors +// ------------------------------------------------------------------- +class ValueErrorsUnknownTypeError extends Error { + constructor(schema) { + super('ValueErrors: Unknown type'); + this.schema = schema; + } +} +exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError; +var ValueErrors; +(function (ValueErrors) { + function* Any(schema, references, path, value) { } + function* Array(schema, references, path, value) { + if (!globalThis.Array.isArray(value)) { + return yield { type: ValueErrorType.Array, schema, path, value, message: `Expected array` }; + } + if (schema.minItems !== undefined && !(value.length >= schema.minItems)) { + yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be greater or equal to ${schema.minItems}` }; + } + if (schema.maxItems !== undefined && !(value.length <= schema.maxItems)) { + yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be less or equal to ${schema.maxItems}` }; + } + if (schema.uniqueItems === true && !(new Set(value).size === value.length)) { + yield { type: ValueErrorType.ArrayUniqueItems, schema, path, value, message: `Expected array elements to be unique` }; + } + for (let i = 0; i < value.length; i++) { + yield* Visit(schema.items, references, `${path}/${i}`, value[i]); + } + } + function* Boolean(schema, references, path, value) { + if (!(typeof value === 'boolean')) { + return yield { type: ValueErrorType.Boolean, schema, path, value, message: `Expected boolean` }; + } + } + function* Constructor(schema, references, path, value) { + yield* Visit(schema.returns, references, path, value.prototype); + } + function* Function(schema, references, path, value) { + if (!(typeof value === 'function')) { + return yield { type: ValueErrorType.Function, schema, path, value, message: `Expected function` }; + } + } + function* Integer(schema, references, path, value) { + if (!(typeof value === 'number')) { + return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` }; + } + if (!globalThis.Number.isInteger(value)) { + yield { type: ValueErrorType.Integer, schema, path, value, message: `Expected integer` }; + } + if (schema.multipleOf && !(value % schema.multipleOf === 0)) { + yield { type: ValueErrorType.IntegerMultipleOf, schema, path, value, message: `Expected integer to be a multiple of ${schema.multipleOf}` }; + } + if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) { + yield { type: ValueErrorType.IntegerExclusiveMinimum, schema, path, value, message: `Expected integer to be greater than ${schema.exclusiveMinimum}` }; + } + if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) { + yield { type: ValueErrorType.IntegerExclusiveMaximum, schema, path, value, message: `Expected integer to be less than ${schema.exclusiveMaximum}` }; + } + if (schema.minimum && !(value >= schema.minimum)) { + yield { type: ValueErrorType.IntegerMinimum, schema, path, value, message: `Expected integer to be greater or equal to ${schema.minimum}` }; + } + if (schema.maximum && !(value <= schema.maximum)) { + yield { type: ValueErrorType.IntegerMaximum, schema, path, value, message: `Expected integer to be less or equal to ${schema.maximum}` }; + } + } + function* Literal(schema, references, path, value) { + if (!(value === schema.const)) { + const error = typeof schema.const === 'string' ? `'${schema.const}'` : schema.const; + return yield { type: ValueErrorType.Literal, schema, path, value, message: `Expected ${error}` }; + } + } + function* Never(schema, references, path, value) { + yield { type: ValueErrorType.Never, schema, path, value, message: `Value cannot be validated` }; + } + function* Null(schema, references, path, value) { + if (!(value === null)) { + return yield { type: ValueErrorType.Null, schema, path, value, message: `Expected null` }; + } + } + function* Number(schema, references, path, value) { + if (!(typeof value === 'number')) { + return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` }; + } + if (schema.multipleOf && !(value % schema.multipleOf === 0)) { + yield { type: ValueErrorType.NumberMultipleOf, schema, path, value, message: `Expected number to be a multiple of ${schema.multipleOf}` }; + } + if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) { + yield { type: ValueErrorType.NumberExclusiveMinimum, schema, path, value, message: `Expected number to be greater than ${schema.exclusiveMinimum}` }; + } + if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) { + yield { type: ValueErrorType.NumberExclusiveMaximum, schema, path, value, message: `Expected number to be less than ${schema.exclusiveMaximum}` }; + } + if (schema.minimum && !(value >= schema.minimum)) { + yield { type: ValueErrorType.NumberMaximum, schema, path, value, message: `Expected number to be greater or equal to ${schema.minimum}` }; + } + if (schema.maximum && !(value <= schema.maximum)) { + yield { type: ValueErrorType.NumberMinumum, schema, path, value, message: `Expected number to be less or equal to ${schema.maximum}` }; + } + } + function* Object(schema, references, path, value) { + if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) { + return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` }; + } + if (schema.minProperties !== undefined && !(globalThis.Object.keys(value).length >= schema.minProperties)) { + yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` }; + } + if (schema.maxProperties !== undefined && !(globalThis.Object.keys(value).length <= schema.maxProperties)) { + yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` }; + } + const propertyKeys = globalThis.Object.keys(schema.properties); + if (schema.additionalProperties === false) { + for (const objectKey of globalThis.Object.keys(value)) { + if (!propertyKeys.includes(objectKey)) { + yield { type: ValueErrorType.ObjectAdditionalProperties, schema, path: `${path}/${objectKey}`, value: value[objectKey], message: `Unexpected property` }; + } + } + } + if (schema.required && schema.required.length > 0) { + const objectKeys = globalThis.Object.keys(value); + for (const requiredKey of schema.required) { + if (objectKeys.includes(requiredKey)) + continue; + yield { type: ValueErrorType.ObjectRequiredProperties, schema: schema.properties[requiredKey], path: `${path}/${requiredKey}`, value: undefined, message: `Expected required property` }; + } + } + if (typeof schema.additionalProperties === 'object') { + for (const objectKey of globalThis.Object.keys(value)) { + if (propertyKeys.includes(objectKey)) + continue; + yield* Visit(schema.additionalProperties, references, `${path}/${objectKey}`, value[objectKey]); + } + } + for (const propertyKey of propertyKeys) { + const propertySchema = schema.properties[propertyKey]; + if (schema.required && schema.required.includes(propertyKey)) { + yield* Visit(propertySchema, references, `${path}/${propertyKey}`, value[propertyKey]); + } + else { + if (value[propertyKey] !== undefined) { + yield* Visit(propertySchema, references, `${path}/${propertyKey}`, value[propertyKey]); + } + } + } + } + function* Promise(schema, references, path, value) { + if (!(typeof value === 'object' && typeof value.then === 'function')) { + yield { type: ValueErrorType.Promise, schema, path, value, message: `Expected Promise` }; + } + } + function* Record(schema, references, path, value) { + if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) { + return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` }; + } + const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; + const regex = new RegExp(keyPattern); + if (!globalThis.Object.keys(value).every((key) => regex.test(key))) { + const numeric = keyPattern === '^(0|[1-9][0-9]*)$'; + const type = numeric ? ValueErrorType.RecordKeyNumeric : ValueErrorType.RecordKeyString; + const message = numeric ? 'Expected all object property keys to be numeric' : 'Expected all object property keys to be strings'; + return yield { type, schema, path, value, message }; + } + for (const [propKey, propValue] of globalThis.Object.entries(value)) { + yield* Visit(valueSchema, references, `${path}/${propKey}`, propValue); + } + } + function* Ref(schema, references, path, value) { + const reference = references.find((reference) => reference.$id === schema.$ref); + if (reference === undefined) + throw new Error(`ValueErrors.Ref: Cannot find schema with $id '${schema.$ref}'.`); + yield* Visit(reference, references, path, value); + } + function* Self(schema, references, path, value) { + const reference = references.find((reference) => reference.$id === schema.$ref); + if (reference === undefined) + throw new Error(`ValueErrors.Self: Cannot find schema with $id '${schema.$ref}'.`); + yield* Visit(reference, references, path, value); + } + function* String(schema, references, path, value) { + if (!(typeof value === 'string')) { + return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' }; + } + if (schema.minLength !== undefined && !(value.length >= schema.minLength)) { + yield { type: ValueErrorType.StringMinLength, schema, path, value, message: `Expected string length greater or equal to ${schema.minLength}` }; + } + if (schema.maxLength !== undefined && !(value.length <= schema.maxLength)) { + yield { type: ValueErrorType.StringMaxLength, schema, path, value, message: `Expected string length less or equal to ${schema.maxLength}` }; + } + if (schema.pattern !== undefined) { + const regex = new RegExp(schema.pattern); + if (!regex.test(value)) { + yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` }; + } + } + if (schema.format !== undefined) { + if (!index_1.Format.Has(schema.format)) { + yield { type: ValueErrorType.StringFormatUnknown, schema, path, value, message: `Unknown string format '${schema.format}'` }; + } + else { + const format = index_1.Format.Get(schema.format); + if (!format(value)) { + yield { type: ValueErrorType.StringFormat, schema, path, value, message: `Expected string to match format '${schema.format}'` }; + } + } + } + } + function* Tuple(schema, references, path, value) { + if (!globalThis.Array.isArray(value)) { + return yield { type: ValueErrorType.Array, schema, path, value, message: 'Expected Array' }; + } + if (schema.items === undefined && !(value.length === 0)) { + return yield { type: ValueErrorType.TupleZeroLength, schema, path, value, message: 'Expected tuple to have 0 elements' }; + } + if (!(value.length === schema.maxItems)) { + yield { type: ValueErrorType.TupleLength, schema, path, value, message: `Expected tuple to have ${schema.maxItems} elements` }; + } + if (!schema.items) { + return; + } + for (let i = 0; i < schema.items.length; i++) { + yield* Visit(schema.items[i], references, `${path}/${i}`, value[i]); + } + } + function* Undefined(schema, references, path, value) { + if (!(value === undefined)) { + yield { type: ValueErrorType.Undefined, schema, path, value, message: `Expected undefined` }; + } + } + function* Union(schema, references, path, value) { + const errors = []; + for (const inner of schema.anyOf) { + const variantErrors = [...Visit(inner, references, path, value)]; + if (variantErrors.length === 0) + return; + errors.push(...variantErrors); + } + for (const error of errors) { + yield error; + } + if (errors.length > 0) { + yield { type: ValueErrorType.Union, schema, path, value, message: 'Expected value of union' }; + } + } + function* Uint8Array(schema, references, path, value) { + if (!(value instanceof globalThis.Uint8Array)) { + return yield { type: ValueErrorType.Uint8Array, schema, path, value, message: `Expected Uint8Array` }; + } + if (schema.maxByteLength && !(value.length <= schema.maxByteLength)) { + yield { type: ValueErrorType.Uint8ArrayMaxByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length less or equal to ${schema.maxByteLength}` }; + } + if (schema.minByteLength && !(value.length >= schema.minByteLength)) { + yield { type: ValueErrorType.Uint8ArrayMinByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length greater or equal to ${schema.maxByteLength}` }; + } + } + function* Unknown(schema, references, path, value) { } + function* Void(schema, references, path, value) { + if (!(value === null)) { + return yield { type: ValueErrorType.Void, schema, path, value, message: `Expected null` }; + } + } + function* Visit(schema, references, path, value) { + const anyReferences = schema.$id === undefined ? references : [schema, ...references]; + const anySchema = schema; + switch (anySchema[Types.Kind]) { + case 'Any': + return yield* Any(anySchema, anyReferences, path, value); + case 'Array': + return yield* Array(anySchema, anyReferences, path, value); + case 'Boolean': + return yield* Boolean(anySchema, anyReferences, path, value); + case 'Constructor': + return yield* Constructor(anySchema, anyReferences, path, value); + case 'Function': + return yield* Function(anySchema, anyReferences, path, value); + case 'Integer': + return yield* Integer(anySchema, anyReferences, path, value); + case 'Literal': + return yield* Literal(anySchema, anyReferences, path, value); + case 'Never': + return yield* Never(anySchema, anyReferences, path, value); + case 'Null': + return yield* Null(anySchema, anyReferences, path, value); + case 'Number': + return yield* Number(anySchema, anyReferences, path, value); + case 'Object': + return yield* Object(anySchema, anyReferences, path, value); + case 'Promise': + return yield* Promise(anySchema, anyReferences, path, value); + case 'Record': + return yield* Record(anySchema, anyReferences, path, value); + case 'Ref': + return yield* Ref(anySchema, anyReferences, path, value); + case 'Self': + return yield* Self(anySchema, anyReferences, path, value); + case 'String': + return yield* String(anySchema, anyReferences, path, value); + case 'Tuple': + return yield* Tuple(anySchema, anyReferences, path, value); + case 'Undefined': + return yield* Undefined(anySchema, anyReferences, path, value); + case 'Union': + return yield* Union(anySchema, anyReferences, path, value); + case 'Uint8Array': + return yield* Uint8Array(anySchema, anyReferences, path, value); + case 'Unknown': + return yield* Unknown(anySchema, anyReferences, path, value); + case 'Void': + return yield* Void(anySchema, anyReferences, path, value); + default: + throw new ValueErrorsUnknownTypeError(schema); + } + } + function* Errors(schema, references, value) { + yield* Visit(schema, references, '', value); + } + ValueErrors.Errors = Errors; +})(ValueErrors = exports.ValueErrors || (exports.ValueErrors = {})); diff --git a/node_modules/@sinclair/typebox/errors/index.d.ts b/node_modules/@sinclair/typebox/errors/index.d.ts new file mode 100644 index 0000000..f72bc43 --- /dev/null +++ b/node_modules/@sinclair/typebox/errors/index.d.ts @@ -0,0 +1 @@ +export * from './errors'; diff --git a/node_modules/@sinclair/typebox/errors/index.js b/node_modules/@sinclair/typebox/errors/index.js new file mode 100644 index 0000000..5f1dd1b --- /dev/null +++ b/node_modules/@sinclair/typebox/errors/index.js @@ -0,0 +1,44 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/errors + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./errors"), exports); diff --git a/node_modules/@sinclair/typebox/format/format.d.ts b/node_modules/@sinclair/typebox/format/format.d.ts new file mode 100644 index 0000000..a1f3406 --- /dev/null +++ b/node_modules/@sinclair/typebox/format/format.d.ts @@ -0,0 +1,12 @@ +export declare type FormatValidationFunction = (value: string) => boolean; +/** Shared string formats used by the TypeCompiler and Value modules */ +export declare namespace Format { + /** Clears all formats */ + function Clear(): void; + /** Returns true if the string format exists */ + function Has(format: string): boolean; + /** Sets a string format validation function */ + function Set(format: string, func: FormatValidationFunction): void; + /** Gets a string format validation function */ + function Get(format: string): FormatValidationFunction | undefined; +} diff --git a/node_modules/@sinclair/typebox/format/format.js b/node_modules/@sinclair/typebox/format/format.js new file mode 100644 index 0000000..df8dccf --- /dev/null +++ b/node_modules/@sinclair/typebox/format/format.js @@ -0,0 +1,55 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/format + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.Format = void 0; +/** Shared string formats used by the TypeCompiler and Value modules */ +var Format; +(function (Format) { + const formats = new Map(); + /** Clears all formats */ + function Clear() { + return formats.clear(); + } + Format.Clear = Clear; + /** Returns true if the string format exists */ + function Has(format) { + return formats.has(format); + } + Format.Has = Has; + /** Sets a string format validation function */ + function Set(format, func) { + formats.set(format, func); + } + Format.Set = Set; + /** Gets a string format validation function */ + function Get(format) { + return formats.get(format); + } + Format.Get = Get; +})(Format = exports.Format || (exports.Format = {})); diff --git a/node_modules/@sinclair/typebox/format/index.d.ts b/node_modules/@sinclair/typebox/format/index.d.ts new file mode 100644 index 0000000..16c5b2b --- /dev/null +++ b/node_modules/@sinclair/typebox/format/index.d.ts @@ -0,0 +1 @@ +export * from './format'; diff --git a/node_modules/@sinclair/typebox/format/index.js b/node_modules/@sinclair/typebox/format/index.js new file mode 100644 index 0000000..f1bcb1d --- /dev/null +++ b/node_modules/@sinclair/typebox/format/index.js @@ -0,0 +1,44 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/format + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./format"), exports); diff --git a/node_modules/@sinclair/typebox/guard/guard.d.ts b/node_modules/@sinclair/typebox/guard/guard.d.ts new file mode 100644 index 0000000..9a4eb4d --- /dev/null +++ b/node_modules/@sinclair/typebox/guard/guard.d.ts @@ -0,0 +1,56 @@ +import * as Types from '../typebox'; +export declare class TypeGuardInvalidTypeError extends Error { + readonly schema: unknown; + constructor(schema: unknown); +} +/** TypeGuard tests that values conform to a known TypeBox type specification */ +export declare namespace TypeGuard { + /** Returns true if the given schema is TAny */ + function TAny(schema: unknown): schema is Types.TAny; + /** Returns true if the given schema is TArray */ + function TArray(schema: unknown): schema is Types.TArray; + /** Returns true if the given schema is TBoolean */ + function TBoolean(schema: unknown): schema is Types.TBoolean; + /** Returns true if the given schema is TConstructor */ + function TConstructor(schema: unknown): schema is Types.TConstructor; + /** Returns true if the given schema is TFunction */ + function TFunction(schema: unknown): schema is Types.TFunction; + /** Returns true if the given schema is TInteger */ + function TInteger(schema: unknown): schema is Types.TInteger; + /** Returns true if the given schema is TLiteral */ + function TLiteral(schema: unknown): schema is Types.TLiteral; + /** Returns true if the given schema is TNever */ + function TNever(schema: unknown): schema is Types.TNever; + /** Returns true if the given schema is TNull */ + function TNull(schema: unknown): schema is Types.TNull; + /** Returns true if the given schema is TNumber */ + function TNumber(schema: unknown): schema is Types.TNumber; + /** Returns true if the given schema is TObject */ + function TObject(schema: unknown): schema is Types.TObject; + /** Returns true if the given schema is TPromise */ + function TPromise(schema: unknown): schema is Types.TPromise; + /** Returns true if the given schema is TRecord */ + function TRecord(schema: unknown): schema is Types.TRecord; + /** Returns true if the given schema is TSelf */ + function TSelf(schema: unknown): schema is Types.TSelf; + /** Returns true if the given schema is TRef */ + function TRef(schema: unknown): schema is Types.TRef; + /** Returns true if the given schema is TString */ + function TString(schema: unknown): schema is Types.TString; + /** Returns true if the given schema is TTuple */ + function TTuple(schema: unknown): schema is Types.TTuple; + /** Returns true if the given schema is TUndefined */ + function TUndefined(schema: unknown): schema is Types.TUndefined; + /** Returns true if the given schema is TUnion */ + function TUnion(schema: unknown): schema is Types.TUnion; + /** Returns true if the given schema is TUint8Array */ + function TUint8Array(schema: unknown): schema is Types.TUint8Array; + /** Returns true if the given schema is TUnknown */ + function TUnknown(schema: unknown): schema is Types.TUnknown; + /** Returns true if the given schema is TVoid */ + function TVoid(schema: unknown): schema is Types.TVoid; + /** Returns true if the given schema is TSchema */ + function TSchema(schema: unknown): schema is Types.TSchema; + /** Asserts if this schema and associated references are valid. */ + function Assert(schema: T, references?: Types.TSchema[]): void; +} diff --git a/node_modules/@sinclair/typebox/guard/guard.js b/node_modules/@sinclair/typebox/guard/guard.js new file mode 100644 index 0000000..82b25f8 --- /dev/null +++ b/node_modules/@sinclair/typebox/guard/guard.js @@ -0,0 +1,351 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/guard + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, dTribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.TypeGuard = exports.TypeGuardInvalidTypeError = void 0; +const Types = require("../typebox"); +class TypeGuardInvalidTypeError extends Error { + constructor(schema) { + super('TypeGuard: Invalid type'); + this.schema = schema; + } +} +exports.TypeGuardInvalidTypeError = TypeGuardInvalidTypeError; +/** TypeGuard tests that values conform to a known TypeBox type specification */ +var TypeGuard; +(function (TypeGuard) { + function IsObject(value) { + return typeof value === 'object' && value !== null && !Array.isArray(value); + } + function IsArray(value) { + return typeof value === 'object' && value !== null && Array.isArray(value); + } + function IsPattern(value) { + try { + new RegExp(value); + return true; + } + catch { + return false; + } + } + function IsControlCharacterFree(value) { + if (typeof value !== 'string') + return false; + for (let i = 0; i < value.length; i++) { + const code = value.charCodeAt(i); + if ((code >= 7 && code <= 13) || code === 27 || code === 127) { + return false; + } + } + return true; + } + function IsString(value) { + return typeof value === 'string'; + } + function IsNumber(value) { + return typeof value === 'number'; + } + function IsBoolean(value) { + return typeof value === 'boolean'; + } + function IsOptionalNumber(value) { + return value === undefined || (value !== undefined && IsNumber(value)); + } + function IsOptionalBoolean(value) { + return value === undefined || (value !== undefined && IsBoolean(value)); + } + function IsOptionalString(value) { + return value === undefined || (value !== undefined && IsString(value)); + } + function IsOptionalPattern(value) { + return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value) && IsPattern(value)); + } + function IsOptionalFormat(value) { + return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value)); + } + function IsOptionalSchema(value) { + return value === undefined || TSchema(value); + } + /** Returns true if the given schema is TAny */ + function TAny(schema) { + return IsObject(schema) && schema[Types.Kind] === 'Any' && IsOptionalString(schema.$id); + } + TypeGuard.TAny = TAny; + /** Returns true if the given schema is TArray */ + function TArray(schema) { + return (IsObject(schema) && + schema[Types.Kind] === 'Array' && + schema.type === 'array' && + IsOptionalString(schema.$id) && + TSchema(schema.items) && + IsOptionalNumber(schema.minItems) && + IsOptionalNumber(schema.maxItems) && + IsOptionalBoolean(schema.uniqueItems)); + } + TypeGuard.TArray = TArray; + /** Returns true if the given schema is TBoolean */ + function TBoolean(schema) { + return IsObject(schema) && schema[Types.Kind] === 'Boolean' && schema.type === 'boolean' && IsOptionalString(schema.$id); + } + TypeGuard.TBoolean = TBoolean; + /** Returns true if the given schema is TConstructor */ + function TConstructor(schema) { + if (!(IsObject(schema) && schema[Types.Kind] === 'Constructor' && schema.type === 'constructor' && IsOptionalString(schema.$id) && IsArray(schema.parameters) && TSchema(schema.returns))) { + return false; + } + for (const parameter of schema.parameters) { + if (!TSchema(parameter)) + return false; + } + return true; + } + TypeGuard.TConstructor = TConstructor; + /** Returns true if the given schema is TFunction */ + function TFunction(schema) { + if (!(IsObject(schema) && schema[Types.Kind] === 'Function' && schema.type === 'function' && IsOptionalString(schema.$id) && IsArray(schema.parameters) && TSchema(schema.returns))) { + return false; + } + for (const parameter of schema.parameters) { + if (!TSchema(parameter)) + return false; + } + return true; + } + TypeGuard.TFunction = TFunction; + /** Returns true if the given schema is TInteger */ + function TInteger(schema) { + return (IsObject(schema) && + schema[Types.Kind] === 'Integer' && + schema.type === 'integer' && + IsOptionalString(schema.$id) && + IsOptionalNumber(schema.multipleOf) && + IsOptionalNumber(schema.minimum) && + IsOptionalNumber(schema.maximum) && + IsOptionalNumber(schema.exclusiveMinimum) && + IsOptionalNumber(schema.exclusiveMaximum)); + } + TypeGuard.TInteger = TInteger; + /** Returns true if the given schema is TLiteral */ + function TLiteral(schema) { + return IsObject(schema) && schema[Types.Kind] === 'Literal' && IsOptionalString(schema.$id) && (IsString(schema.const) || IsNumber(schema.const) || IsBoolean(schema.const)); + } + TypeGuard.TLiteral = TLiteral; + /** Returns true if the given schema is TNever */ + function TNever(schema) { + return (IsObject(schema) && + schema[Types.Kind] === 'Never' && + IsArray(schema.allOf) && + schema.allOf.length === 2 && + IsObject(schema.allOf[0]) && + IsString(schema.allOf[0].type) && + schema.allOf[0].type === 'boolean' && + schema.allOf[0].const === false && + IsObject(schema.allOf[1]) && + IsString(schema.allOf[1].type) && + schema.allOf[1].type === 'boolean' && + schema.allOf[1].const === true); + } + TypeGuard.TNever = TNever; + /** Returns true if the given schema is TNull */ + function TNull(schema) { + return IsObject(schema) && schema[Types.Kind] === 'Null' && schema.type === 'null' && IsOptionalString(schema.$id); + } + TypeGuard.TNull = TNull; + /** Returns true if the given schema is TNumber */ + function TNumber(schema) { + return (IsObject(schema) && + schema[Types.Kind] === 'Number' && + schema.type === 'number' && + IsOptionalString(schema.$id) && + IsOptionalNumber(schema.multipleOf) && + IsOptionalNumber(schema.minimum) && + IsOptionalNumber(schema.maximum) && + IsOptionalNumber(schema.exclusiveMinimum) && + IsOptionalNumber(schema.exclusiveMaximum)); + } + TypeGuard.TNumber = TNumber; + /** Returns true if the given schema is TObject */ + function TObject(schema) { + if (!(IsObject(schema) && + schema[Types.Kind] === 'Object' && + schema.type === 'object' && + IsOptionalString(schema.$id) && + IsObject(schema.properties) && + (IsOptionalBoolean(schema.additionalProperties) || IsOptionalSchema(schema.additionalProperties)) && + IsOptionalNumber(schema.minProperties) && + IsOptionalNumber(schema.maxProperties))) { + return false; + } + for (const [key, value] of Object.entries(schema.properties)) { + if (!IsControlCharacterFree(key)) + return false; + if (!TSchema(value)) + return false; + } + return true; + } + TypeGuard.TObject = TObject; + /** Returns true if the given schema is TPromise */ + function TPromise(schema) { + return IsObject(schema) && schema[Types.Kind] === 'Promise' && schema.type === 'promise' && IsOptionalString(schema.$id) && TSchema(schema.item); + } + TypeGuard.TPromise = TPromise; + /** Returns true if the given schema is TRecord */ + function TRecord(schema) { + if (!(IsObject(schema) && schema[Types.Kind] === 'Record' && schema.type === 'object' && IsOptionalString(schema.$id) && schema.additionalProperties === false && IsObject(schema.patternProperties))) { + return false; + } + const keys = Object.keys(schema.patternProperties); + if (keys.length !== 1) { + return false; + } + if (!IsPattern(keys[0])) { + return false; + } + if (!TSchema(schema.patternProperties[keys[0]])) { + return false; + } + return true; + } + TypeGuard.TRecord = TRecord; + /** Returns true if the given schema is TSelf */ + function TSelf(schema) { + return IsObject(schema) && schema[Types.Kind] === 'Self' && IsOptionalString(schema.$id) && IsString(schema.$ref); + } + TypeGuard.TSelf = TSelf; + /** Returns true if the given schema is TRef */ + function TRef(schema) { + return IsObject(schema) && schema[Types.Kind] === 'Ref' && IsOptionalString(schema.$id) && IsString(schema.$ref); + } + TypeGuard.TRef = TRef; + /** Returns true if the given schema is TString */ + function TString(schema) { + return (IsObject(schema) && + schema[Types.Kind] === 'String' && + schema.type === 'string' && + IsOptionalString(schema.$id) && + IsOptionalNumber(schema.minLength) && + IsOptionalNumber(schema.maxLength) && + IsOptionalPattern(schema.pattern) && + IsOptionalFormat(schema.format)); + } + TypeGuard.TString = TString; + /** Returns true if the given schema is TTuple */ + function TTuple(schema) { + if (!(IsObject(schema) && schema[Types.Kind] === 'Tuple' && schema.type === 'array' && IsOptionalString(schema.$id) && IsNumber(schema.minItems) && IsNumber(schema.maxItems) && schema.minItems === schema.maxItems)) { + return false; + } + if (schema.items === undefined && schema.additionalItems === undefined && schema.minItems === 0) { + return true; + } + if (!IsArray(schema.items)) { + return false; + } + for (const inner of schema.items) { + if (!TSchema(inner)) + return false; + } + return true; + } + TypeGuard.TTuple = TTuple; + /** Returns true if the given schema is TUndefined */ + function TUndefined(schema) { + return IsObject(schema) && schema[Types.Kind] === 'Undefined' && schema.type === 'object' && IsOptionalString(schema.$id) && schema.specialized === 'Undefined'; + } + TypeGuard.TUndefined = TUndefined; + /** Returns true if the given schema is TUnion */ + function TUnion(schema) { + if (!(IsObject(schema) && schema[Types.Kind] === 'Union' && IsArray(schema.anyOf) && IsOptionalString(schema.$id))) { + return false; + } + for (const inner of schema.anyOf) { + if (!TSchema(inner)) + return false; + } + return true; + } + TypeGuard.TUnion = TUnion; + /** Returns true if the given schema is TUint8Array */ + function TUint8Array(schema) { + return (IsObject(schema) && + schema[Types.Kind] === 'Uint8Array' && + schema.type === 'object' && + IsOptionalString(schema.$id) && + schema.specialized === 'Uint8Array' && + IsOptionalNumber(schema.minByteLength) && + IsOptionalNumber(schema.maxByteLength)); + } + TypeGuard.TUint8Array = TUint8Array; + /** Returns true if the given schema is TUnknown */ + function TUnknown(schema) { + return IsObject(schema) && schema[Types.Kind] === 'Unknown' && IsOptionalString(schema.$id); + } + TypeGuard.TUnknown = TUnknown; + /** Returns true if the given schema is TVoid */ + function TVoid(schema) { + return IsObject(schema) && schema[Types.Kind] === 'Void' && schema.type === 'null' && IsOptionalString(schema.$id); + } + TypeGuard.TVoid = TVoid; + /** Returns true if the given schema is TSchema */ + function TSchema(schema) { + return (TAny(schema) || + TArray(schema) || + TBoolean(schema) || + TConstructor(schema) || + TFunction(schema) || + TInteger(schema) || + TLiteral(schema) || + TNever(schema) || + TNull(schema) || + TNumber(schema) || + TObject(schema) || + TPromise(schema) || + TRecord(schema) || + TSelf(schema) || + TRef(schema) || + TString(schema) || + TTuple(schema) || + TUndefined(schema) || + TUnion(schema) || + TUint8Array(schema) || + TUnknown(schema) || + TVoid(schema)); + } + TypeGuard.TSchema = TSchema; + /** Asserts if this schema and associated references are valid. */ + function Assert(schema, references = []) { + if (!TSchema(schema)) + throw new TypeGuardInvalidTypeError(schema); + for (const schema of references) { + if (!TSchema(schema)) + throw new TypeGuardInvalidTypeError(schema); + } + } + TypeGuard.Assert = Assert; +})(TypeGuard = exports.TypeGuard || (exports.TypeGuard = {})); diff --git a/node_modules/@sinclair/typebox/guard/index.d.ts b/node_modules/@sinclair/typebox/guard/index.d.ts new file mode 100644 index 0000000..def4962 --- /dev/null +++ b/node_modules/@sinclair/typebox/guard/index.d.ts @@ -0,0 +1 @@ +export * from './guard'; diff --git a/node_modules/@sinclair/typebox/guard/index.js b/node_modules/@sinclair/typebox/guard/index.js new file mode 100644 index 0000000..872c8dd --- /dev/null +++ b/node_modules/@sinclair/typebox/guard/index.js @@ -0,0 +1,44 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/guards + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(require("./guard"), exports); diff --git a/node_modules/@sinclair/typebox/license b/node_modules/@sinclair/typebox/license new file mode 100644 index 0000000..cd929d3 --- /dev/null +++ b/node_modules/@sinclair/typebox/license @@ -0,0 +1,23 @@ +TypeBox: JSON Schema Type Builder with Static Type Resolution for TypeScript + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@sinclair/typebox/package.json b/node_modules/@sinclair/typebox/package.json new file mode 100644 index 0000000..a4b4814 --- /dev/null +++ b/node_modules/@sinclair/typebox/package.json @@ -0,0 +1,40 @@ +{ + "name": "@sinclair/typebox", + "version": "0.24.51", + "description": "JSONSchema Type Builder with Static Type Resolution for TypeScript", + "keywords": [ + "typescript", + "json-schema", + "validate", + "typecheck" + ], + "author": "sinclairzx81", + "license": "MIT", + "main": "./typebox.js", + "types": "./typebox.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/sinclairzx81/typebox" + }, + "scripts": { + "clean": "hammer task clean", + "format": "hammer task format", + "start": "hammer task start", + "test": "hammer task test", + "benchmark": "hammer task benchmark", + "build": "hammer task build", + "publish": "hammer task publish" + }, + "devDependencies": { + "@sinclair/hammer": "^0.17.1", + "@types/chai": "^4.3.3", + "@types/mocha": "^9.1.1", + "@types/node": "^18.7.13", + "ajv": "^8.11.0", + "ajv-formats": "^2.1.1", + "chai": "^4.3.6", + "mocha": "^9.2.2", + "prettier": "^2.7.1", + "typescript": "^4.8.2" + } +} diff --git a/node_modules/@sinclair/typebox/readme.md b/node_modules/@sinclair/typebox/readme.md new file mode 100644 index 0000000..a5bc4ca --- /dev/null +++ b/node_modules/@sinclair/typebox/readme.md @@ -0,0 +1,1152 @@ +

+ +

TypeBox

+ +

JSON Schema Type Builder with Static Type Resolution for TypeScript

+ + + +
+
+ +[![npm version](https://badge.fury.io/js/%40sinclair%2Ftypebox.svg)](https://badge.fury.io/js/%40sinclair%2Ftypebox) +[![Downloads](https://img.shields.io/npm/dm/%40sinclair%2Ftypebox.svg)](https://www.npmjs.com/package/%40sinclair%2Ftypebox) +[![GitHub CI](https://github.com/sinclairzx81/typebox/workflows/GitHub%20CI/badge.svg)](https://github.com/sinclairzx81/typebox/actions) + +
+ +
+ +## Install + +Node + +```bash +$ npm install @sinclair/typebox --save +``` + +Deno and ESM + +```typescript +import { Static, Type } from 'https://esm.sh/@sinclair/typebox' +``` + +## Example + +```typescript +import { Static, Type } from '@sinclair/typebox' + +const T = Type.String() // const T = { type: 'string' } + +type T = Static // type T = string +``` + + + +## Overview + +TypeBox is a type builder library that creates in-memory JSON Schema objects that can be statically inferred as TypeScript types. The schemas produced by this library are designed to match the static type checking rules of the TypeScript compiler. TypeBox enables one to create a unified type that can be statically checked by TypeScript and runtime asserted using standard JSON Schema validation. + +TypeBox is designed to enable JSON schema to compose with the same flexibility as TypeScript's type system. It can be used either as a simple tool to build up complex schemas or integrated into REST and RPC services to help validate data received over the wire. + +License MIT + +## Contents +- [Install](#install) +- [Overview](#overview) +- [Usage](#usage) +- [Types](#types) + - [Standard](#types-standard) + - [Modifiers](#types-modifiers) + - [Options](#types-options) + - [Extended](#types-extended) + - [Reference](#types-reference) + - [Recursive](#types-recursive) + - [Generic](#types-generic) + - [Conditional](#types-conditional) + - [Unsafe](#types-unsafe) + - [Guards](#types-guards) + - [Strict](#types-strict) +- [Values](#values) + - [Create](#values-create) + - [Clone](#values-clone) + - [Check](#values-check) + - [Cast](#values-cast) + - [Equal](#values-equal) + - [Diff](#values-diff) + - [Patch](#values-patch) + - [Errors](#values-errors) + - [Pointer](#values-pointer) +- [TypeCheck](#typecheck) + - [Ajv](#typecheck-ajv) + - [Compiler](#typecheck-compiler) + - [Formats](#typecheck-formats) +- [Benchmark](#benchmark) + - [Compile](#benchmark-compile) + - [Validate](#benchmark-validate) + - [Compression](#benchmark-compression) +- [Contribute](#contribute) + + + +## Usage + +The following demonstrates TypeBox's general usage. + +```typescript + +import { Static, Type } from '@sinclair/typebox' + +//-------------------------------------------------------------------------------------------- +// +// Let's say you have the following type ... +// +//-------------------------------------------------------------------------------------------- + +type T = { + id: string, + name: string, + timestamp: number +} + +//-------------------------------------------------------------------------------------------- +// +// ... you can express this type in the following way. +// +//-------------------------------------------------------------------------------------------- + +const T = Type.Object({ // const T = { + id: Type.String(), // type: 'object', + name: Type.String(), // properties: { + timestamp: Type.Integer() // id: { +}) // type: 'string' + // }, + // name: { + // type: 'string' + // }, + // timestamp: { + // type: 'integer' + // } + // }, + // required: [ + // 'id', + // 'name', + // 'timestamp' + // ] + // } + +//-------------------------------------------------------------------------------------------- +// +// ... then infer back to the original static type this way. +// +//-------------------------------------------------------------------------------------------- + +type T = Static // type T = { + // id: string, + // name: string, + // timestamp: number + // } + +//-------------------------------------------------------------------------------------------- +// +// ... then use the type both as JSON schema and as a TypeScript type. +// +//-------------------------------------------------------------------------------------------- + +function receive(value: T) { // ... as a Type + + if(JSON.validate(T, value)) { // ... as a Schema + + // ok... + } +} +``` + + + +## Types + +TypeBox provides a set of functions that allow you to compose JSON Schema similar to how you would compose static types with TypeScript. Each function creates a JSON schema fragment which can compose into more complex types. The schemas produced by TypeBox can be passed directly to any JSON Schema compliant validator, or used to reflect runtime metadata for a type. + + + +### Standard + +The following table lists the standard TypeBox types. + +```typescript +┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐ +│ TypeBox │ TypeScript │ JSON Schema │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Any() │ type T = any │ const T = { } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Unknown() │ type T = unknown │ const T = { } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.String() │ type T = string │ const T = { │ +│ │ │ type: 'string' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Number() │ type T = number │ const T = { │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Integer() │ type T = number │ const T = { │ +│ │ │ type: 'integer' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Boolean() │ type T = boolean │ const T = { │ +│ │ │ type: 'boolean' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Null() │ type T = null │ const T = { │ +│ │ │ type: 'null' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.RegEx(/foo/) │ type T = string │ const T = { │ +│ │ │ type: 'string', │ +│ │ │ pattern: 'foo' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Literal(42) │ type T = 42 │ const T = { │ +│ │ │ const: 42, │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Array( │ type T = number[] │ const T = { │ +│ Type.Number() │ │ type: 'array', │ +│ ) │ │ items: { │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Object({ │ type T = { │ const T = { │ +│ x: Type.Number(), │ x: number, │ type: 'object', │ +│ y: Type.Number() │ y: number │ properties: { │ +│ }) │ } │ x: { │ +│ │ │ type: 'number' │ +│ │ │ }, │ +│ │ │ y: { │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ }, │ +│ │ │ required: ['x', 'y'] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Tuple([ │ type T = [number, number] │ const T = { │ +│ Type.Number(), │ │ type: 'array', │ +│ Type.Number() │ │ items: [{ │ +│ ]) │ │ type: 'number' │ +│ │ │ }, { │ +│ │ │ type: 'number' │ +│ │ │ }], │ +│ │ │ additionalItems: false, │ +│ │ │ minItems: 2, │ +│ │ │ maxItems: 2 │ +│ │ │ } │ +│ │ │ │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ enum Foo { │ enum Foo { │ const T = { │ +│ A, │ A, │ anyOf: [{ │ +│ B │ B │ type: 'number', │ +│ } │ } │ const: 0 │ +│ │ │ }, { │ +│ const T = Type.Enum(Foo) │ type T = Foo │ type: 'number', │ +│ │ │ const: 1 │ +│ │ │ }] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.KeyOf( │ type T = keyof { │ const T = { │ +│ Type.Object({ │ x: number, │ anyOf: [{ │ +│ x: Type.Number(), │ y: number │ type: 'string', │ +│ y: Type.Number() │ } │ const: 'x' │ +│ }) │ │ }, { │ +│ ) │ │ type: 'string', │ +│ │ │ const: 'y' │ +│ │ │ }] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Union([ │ type T = string | number │ const T = { │ +│ Type.String(), │ │ anyOf: [{ │ +│ Type.Number() │ │ type: 'string' │ +│ ]) │ │ }, { │ +│ │ │ type: 'number' │ +│ │ │ }] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Intersect([ │ type T = { │ const T = { │ +│ Type.Object({ │ x: number │ type: 'object', │ +│ x: Type.Number() │ } & { │ properties: { │ +│ }), │ y: number │ x: { │ +│ Type.Object({ │ } │ type: 'number' │ +│ y: Type.Number() │ │ }, │ +│ }) │ │ y: { │ +│ ]) │ │ type: 'number' │ +│ │ │ } │ +│ │ │ }, │ +│ │ │ required: ['x', 'y'] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Never() │ type T = never │ const T = { │ +│ │ │ allOf: [{ │ +│ │ │ type: 'boolean', │ +│ │ │ const: false │ +│ │ │ }, { │ +│ │ │ type: 'boolean', │ +│ │ │ const: true │ +│ │ │ }] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Record( │ type T = Record< │ const T = { │ +│ Type.String(), │ string, │ type: 'object', │ +│ Type.Number() │ number, │ patternProperties: { │ +│ ) │ > │ '^.*$': { │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Partial( │ type T = Partial<{ │ const T = { │ +│ Type.Object({ │ x: number, │ type: 'object', │ +│ x: Type.Number(), │ y: number │ properties: { │ +│ y: Type.Number() | }> │ x: { │ +│ }) │ │ type: 'number' │ +│ ) │ │ }, │ +│ │ │ y: { │ +│ │ │ type: 'number' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Required( │ type T = Required<{ │ const T = { │ +│ Type.Object({ │ x?: number, │ type: 'object', │ +│ x: Type.Optional( │ y?: number │ properties: { │ +│ Type.Number() | }> │ x: { │ +│ ), │ │ type: 'number' │ +│ y: Type.Optional( │ │ }, │ +│ Type.Number() │ │ y: { │ +│ ) │ │ type: 'number' │ +│ }) │ │ } │ +│ ) │ │ }, │ +│ │ │ required: ['x', 'y'] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Pick( │ type T = Pick<{ │ const T = { │ +│ Type.Object({ │ x: number, │ type: 'object', │ +│ x: Type.Number(), │ y: number │ properties: { │ +│ y: Type.Number() | }, 'x'> │ x: { │ +│ }), ['x'] │ │ type: 'number' │ +│ ) │ │ } │ +│ │ │ }, │ +│ │ │ required: ['x'] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Omit( │ type T = Omit<{ │ const T = { │ +│ Type.Object({ │ x: number, │ type: 'object', │ +│ x: Type.Number(), │ y: number │ properties: { │ +│ y: Type.Number() | }, 'x'> │ y: { │ +│ }), ['x'] │ │ type: 'number' │ +│ ) │ │ } │ +│ │ │ }, │ +│ │ │ required: ['y'] │ +│ │ │ } │ +│ │ │ │ +└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘ +``` + + + +### Modifiers + +TypeBox provides modifiers that can be applied to an objects properties. This allows for `optional` and `readonly` to be applied to that property. The following table illustates how they map between TypeScript and JSON Schema. + +```typescript +┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐ +│ TypeBox │ TypeScript │ JSON Schema │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Object({ │ type T = { │ const T = { │ +│ name: Type.Optional( │ name?: string │ type: 'object', │ +│ Type.String() │ } │ properties: { │ +│ ) │ │ name: { │ +│ }) │ │ type: 'string' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Object({ │ type T = { │ const T = { │ +│ name: Type.Readonly( │ readonly name: string │ type: 'object', │ +│ Type.String() │ } │ properties: { │ +│ ) │ │ name: { │ +│ }) │ │ type: 'string' │ +│ │ │ } │ +│ │ │ }, │ +│ │ │ required: ['name'] │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Object({ │ type T = { │ const T = { │ +│ name: Type.ReadonlyOptional( │ readonly name?: string │ type: 'object', │ +│ Type.String() │ } │ properties: { │ +│ ) │ │ name: { │ +│ }) │ │ type: 'string' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘ +``` + + + +### Options + +You can pass additional JSON schema options on the last argument of any given type. The following are some examples. + +```typescript +// string must be an email +const T = Type.String({ format: 'email' }) + +// number must be a multiple of 2 +const T = Type.Number({ multipleOf: 2 }) + +// array must have at least 5 integer values +const T = Type.Array(Type.Integer(), { minItems: 5 }) +``` + + + +### Extended + +In addition to JSON schema types, TypeBox provides several extended types that allow for the composition of `function` and `constructor` types. These additional types are not valid JSON Schema and will not validate using typical JSON Schema validation. However, these types can be used to frame JSON schema and describe callable interfaces that may receive JSON validated data. These types are as follows. + +```typescript +┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐ +│ TypeBox │ TypeScript │ Extended Schema │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Constructor([ │ type T = new ( │ const T = { │ +│ Type.String(), │ arg0: string, │ type: 'constructor' │ +│ Type.Number() │ arg1: number │ parameters: [{ │ +│ ], Type.Boolean()) │ ) => boolean │ type: 'string' │ +│ │ │ }, { │ +│ │ │ type: 'number' │ +│ │ │ }], │ +│ │ │ return: { │ +│ │ │ type: 'boolean' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Function([ │ type T = ( │ const T = { │ +| Type.String(), │ arg0: string, │ type : 'function', │ +│ Type.Number() │ arg1: number │ parameters: [{ │ +│ ], Type.Boolean()) │ ) => boolean │ type: 'string' │ +│ │ │ }, { │ +│ │ │ type: 'number' │ +│ │ │ }], │ +│ │ │ return: { │ +│ │ │ type: 'boolean' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Uint8Array() │ type T = Uint8Array │ const T = { │ +│ │ │ type: 'object', │ +│ │ │ specialized: 'Uint8Array' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Promise( │ type T = Promise │ const T = { │ +│ Type.String() │ │ type: 'promise', │ +│ ) │ │ item: { │ +│ │ │ type: 'string' │ +│ │ │ } │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Undefined() │ type T = undefined │ const T = { │ +│ │ │ type: 'object', │ +│ │ │ specialized: 'Undefined' │ +│ │ │ } │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Type.Void() │ type T = void │ const T = { │ +│ │ │ type: 'null' │ +│ │ │ } │ +│ │ │ │ +└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘ +``` + + + +### Reference + +Use `Type.Ref(...)` to create referenced types. The target type must specify an `$id`. + +```typescript +const T = Type.String({ $id: 'T' }) // const T = { + // $id: 'T', + // type: 'string' + // } + +const R = Type.Ref(T) // const R = { + // $ref: 'T' + // } +``` + + + +### Recursive + +Use `Type.Recursive(...)` to create recursive types. + +```typescript +const Node = Type.Recursive(Node => Type.Object({ // const Node = { + id: Type.String(), // $id: 'Node', + nodes: Type.Array(Node) // type: 'object', +}), { $id: 'Node' }) // properties: { + // id: { + // type: 'string' + // }, + // nodes: { + // type: 'array', + // items: { + // $ref: 'Node' + // } + // } + // }, + // required: [ + // 'id', + // 'nodes' + // ] + // } + +type Node = Static // type Node = { + // id: string + // nodes: Node[] + // } + +function test(node: Node) { + const id = node.nodes[0].nodes[0] // id is string + .nodes[0].nodes[0] + .id +} +``` + + + +### Generic + +Use functions to create generic types. The following creates a generic `Nullable` type. + +```typescript +import { Type, Static, TSchema } from '@sinclair/typebox' + +const Nullable = (type: T) => Type.Union([type, Type.Null()]) + +const T = Nullable(Type.String()) // const T = { + // anyOf: [{ + // type: 'string' + // }, { + // type: 'null' + // }] + // } + +type T = Static // type T = string | null + +const U = Nullable(Type.Number()) // const U = { + // anyOf: [{ + // type: 'number' + // }, { + // type: 'null' + // }] + // } + +type U = Static // type U = number | null +``` + + + +### Conditional + +Use the conditional module to create [Conditional Types](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html). This module implements TypeScript's structural equivalence checks to enable TypeBox types to be conditionally inferred at runtime. This module also provides the [Extract](https://www.typescriptlang.org/docs/handbook/utility-types.html#extracttype-union) and [Exclude](https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers) utility types which are expressed as conditional types in TypeScript. + +The conditional module is provided as an optional import. + +```typescript +import { Conditional } from '@sinclair/typebox/conditional' +``` +The following table shows the TypeBox mappings between TypeScript and JSON schema. + +```typescript +┌────────────────────────────────┬─────────────────────────────┬────────────────────────────────┐ +│ TypeBox │ TypeScript │ JSON Schema │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Conditional.Extends( │ type T = │ const T = { │ +│ Type.String(), │ string extends number │ const: false, │ +│ Type.Number(), │ true : false │ type: 'boolean' │ +│ Type.Literal(true), │ │ } │ +│ Type.Literal(false) │ │ │ +│ ) │ │ │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Conditional.Extract( │ type T = Extract< │ const T = { │ +│ Type.Union([ │ 'a' | 'b' | 'c', │ anyOf: [{ │ +│ Type.Literal('a'), │ 'a' | 'f' │ const: 'a' │ +│ Type.Literal('b'), │ > │ type: 'string' │ +│ Type.Literal('c') │ │ }] │ +│ ]), │ │ } │ +│ Type.Union([ │ │ │ +│ Type.Literal('a'), │ │ │ +│ Type.Literal('f') │ │ │ +│ ]) │ │ │ +│ ) │ │ │ +│ │ │ │ +├────────────────────────────────┼─────────────────────────────┼────────────────────────────────┤ +│ const T = Conditional.Exclude( │ type T = Exclude< │ const T = { │ +│ Type.Union([ │ 'a' | 'b' | 'c', │ anyOf: [{ │ +│ Type.Literal('a'), │ 'a' │ const: 'b', │ +│ Type.Literal('b'), │ > │ type: 'string' │ +│ Type.Literal('c') │ │ }, { │ +│ ]), │ │ const: 'c', │ +│ Type.Union([ │ │ type: 'string' │ +│ Type.Literal('a') │ │ }] │ +│ ]) │ │ } │ +│ ) │ │ │ +│ │ │ │ +└────────────────────────────────┴─────────────────────────────┴────────────────────────────────┘ +``` + + + +### Unsafe + +Use `Type.Unsafe(...)` to create custom schemas with user defined inference rules. + +```typescript +const T = Type.Unsafe({ type: 'number' }) // const T = { + // type: 'number' + // } + +type T = Static // type T = string +``` + +This function can be used to create custom schemas for validators that require specific schema representations. An example of this might be OpenAPI's `nullable` and `enum` schemas which are not provided by TypeBox. The following demonstrates using `Type.Unsafe(...)` to create these types. + +```typescript +import { Type, Static, TSchema } from '@sinclair/typebox' + +//-------------------------------------------------------------------------------------------- +// +// Nullable +// +//-------------------------------------------------------------------------------------------- + +function Nullable(schema: T) { + return Type.Unsafe | null>({ ...schema, nullable: true }) +} + +const T = Nullable(Type.String()) // const T = { + // type: 'string', + // nullable: true + // } + +type T = Static // type T = string | null + + +//-------------------------------------------------------------------------------------------- +// +// StringEnum +// +//-------------------------------------------------------------------------------------------- + +function StringEnum(values: [...T]) { + return Type.Unsafe({ type: 'string', enum: values }) +} + +const T = StringEnum(['A', 'B', 'C']) // const T = { + // enum: ['A', 'B', 'C'] + // } + +type T = Static // type T = 'A' | 'B' | 'C' +``` + + + +### Guards + +Use the guard module to test if values are TypeBox types. + +```typescript +import { TypeGuard } from '@sinclair/typebox/guard' + +const T = Type.String() + +if(TypeGuard.TString(T)) { + + // T is TString +} +``` + + + +### Strict + +TypeBox schemas contain the `Kind` and `Modifier` symbol properties. These properties are provided to enable runtime type reflection on schemas, as well as helping TypeBox internally compose types. These properties are not strictly valid JSON schema; so in some cases it may be desirable to omit them. TypeBox provides a `Type.Strict()` function that will omit these properties if necessary. + +```typescript +const T = Type.Object({ // const T = { + name: Type.Optional(Type.String()) // [Kind]: 'Object', +}) // type: 'object', + // properties: { + // name: { + // [Kind]: 'String', + // type: 'string', + // [Modifier]: 'Optional' + // } + // } + // } + +const U = Type.Strict(T) // const U = { + // type: 'object', + // properties: { + // name: { + // type: 'string' + // } + // } + // } +``` + + + +## Values + +TypeBox includes an optional values module that can be used to perform common operations on JavaScript values. This module enables one to create, check and cast values from types. It also provides functionality to check equality, clone and diff and patch JavaScript values. The value module is provided as an optional import. + +```typescript +import { Value } from '@sinclair/typebox/value' +``` + + + +### Create + +Use the Create function to create a value from a TypeBox type. TypeBox will use default values if specified. + +```typescript +const T = Type.Object({ x: Type.Number(), y: Type.Number({ default: 42 }) }) + +const A = Value.Create(T) // const A = { x: 0, y: 42 } +``` + + + +### Clone + +Use the Clone function to deeply clone a value + +```typescript +const A = Value.Clone({ x: 1, y: 2, z: 3 }) // const A = { x: 1, y: 2, z: 3 } +``` + + + +### Check + +Use the Check function to type check a value + +```typescript +const T = Type.Object({ x: Type.Number() }) + +const R = Value.Check(T, { x: 1 }) // const R = true +``` + + + +### Cast + +Use the Cast function to cast a value into a type. The cast function will retain as much information as possible from the original value. + +```typescript +const T = Type.Object({ x: Type.Number(), y: Type.Number() }, { additionalProperties: false }) + +const X = Value.Cast(T, null) // const X = { x: 0, y: 0 } + +const Y = Value.Cast(T, { x: 1 }) // const Y = { x: 1, y: 0 } + +const Z = Value.Cast(T, { x: 1, y: 2, z: 3 }) // const Z = { x: 1, y: 2 } +``` + + + +### Equal + +Use the Equal function to deeply check for value equality. + +```typescript +const R = Value.Equal( // const R = true + { x: 1, y: 2, z: 3 }, + { x: 1, y: 2, z: 3 } +) +``` + + + +### Diff + +Use the Diff function to produce a sequence of edits to transform one value into another. + +```typescript +const E = Value.Diff( // const E = [ + { x: 1, y: 2, z: 3 }, // { type: 'update', path: '/y', value: 4 }, + { y: 4, z: 5, w: 6 } // { type: 'update', path: '/z', value: 5 }, +) // { type: 'insert', path: '/w', value: 6 }, + // { type: 'delete', path: '/x' } + // ] +``` + + + +### Patch + +Use the Patch function to apply edits + +```typescript +const A = { x: 1, y: 2 } + +const B = { x: 3 } + +const E = Value.Diff(A, B) // const E = [ + // { type: 'update', path: '/x', value: 3 }, + // { type: 'delete', path: '/y' } + // ] + +const C = Value.Patch(A, E) // const C = { x: 3 } +``` + + + + +### Errors + +Use the Errors function enumerate validation errors. + +```typescript +const T = Type.Object({ x: Type.Number(), y: Type.Number() }) + +const R = [...Value.Errors(T, { x: '42' })] // const R = [{ + // schema: { type: 'number' }, + // path: '/x', + // value: '42', + // message: 'Expected number' + // }, { + // schema: { type: 'number' }, + // path: '/y', + // value: undefined, + // message: 'Expected number' + // }] +``` + + + +### Pointer + +Use ValuePointer to perform mutable updates on existing values using [RFC6901](https://www.rfc-editor.org/rfc/rfc6901) Json Pointers. + +```typescript +import { ValuePointer } from '@sinclair/typebox/value' + +const A = { x: 0, y: 0, z: 0 } + +ValuePointer.Set(A, '/x', 1) // const A = { x: 1, y: 0, z: 0 } +ValuePointer.Set(A, '/y', 1) // const A = { x: 1, y: 1, z: 0 } +ValuePointer.Set(A, '/z', 1) // const A = { x: 1, y: 1, z: 1 } +``` + + +## TypeCheck + +TypeBox is written to target JSON Schema Draft 6 and can be used with any Draft 6 compliant validator. TypeBox is developed and tested against Ajv and can be used in any application already making use of this validator. Additionally, TypeBox also provides an optional type compiler that can be used to attain improved compilation and validation performance for certain application types. + + + +### Ajv + +The following example shows setting up Ajv to work with TypeBox. + +```bash +$ npm install ajv ajv-formats --save +``` + +```typescript +import { Type } from '@sinclair/typebox' +import addFormats from 'ajv-formats' +import Ajv from 'ajv' + +//-------------------------------------------------------------------------------------------- +// +// Setup Ajv validator with the following options and formats +// +//-------------------------------------------------------------------------------------------- + +const ajv = addFormats(new Ajv({}), [ + 'date-time', + 'time', + 'date', + 'email', + 'hostname', + 'ipv4', + 'ipv6', + 'uri', + 'uri-reference', + 'uuid', + 'uri-template', + 'json-pointer', + 'relative-json-pointer', + 'regex' +]) + +//-------------------------------------------------------------------------------------------- +// +// Create a TypeBox type +// +//-------------------------------------------------------------------------------------------- + +const T = Type.Object({ + x: Type.Number(), + y: Type.Number(), + z: Type.Number() +}) + +//-------------------------------------------------------------------------------------------- +// +// Validate Data +// +//-------------------------------------------------------------------------------------------- + +const R = ajv.validate(T, { x: 1, y: 2, z: 3 }) // const R = true +``` + + + +### Compiler + +TypeBox provides an optional high performance just-in-time (JIT) compiler and type checker that can be used in applications that require extremely fast validation. Note that this compiler is optimized for TypeBox types only where the schematics are known in advance. If defining custom types with `Type.Unsafe` please consider Ajv. + +The compiler module is provided as an optional import. + +```typescript +import { TypeCompiler } from '@sinclair/typebox/compiler' +``` + +Use the `Compile(...)` function to compile a type. + +```typescript +const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck> + +const R = C.Check({ x: 1, y: 2, z: 3 }) // const R = true +``` + +Validation errors can be read with the `Errors(...)` function. + +```typescript +const C = TypeCompiler.Compile(Type.Object({ // const C: TypeCheck> + +const value = { } + +const errors = [...C.Errors(value)] // const errors = [{ + // schema: { type: 'number' }, + // path: '/x', + // value: undefined, + // message: 'Expected number' + // }, { + // schema: { type: 'number' }, + // path: '/y', + // value: undefined, + // message: 'Expected number' + // }, { + // schema: { type: 'number' }, + // path: '/z', + // value: undefined, + // message: 'Expected number' + // }] +``` + +Compiled routines can be inspected with the `.Code()` function. + +```typescript +const C = TypeCompiler.Compile(Type.String()) // const C: TypeCheck + +console.log(C.Code()) // return function check(value) { + // return ( + // (typeof value === 'string') + // ) + // } +``` + + + +### Formats + +Use the format module to create user defined string formats. The format module is used by the Value and TypeCompiler modules only. If using Ajv, please refer to the official Ajv format documentation located [here](https://ajv.js.org/guide/formats.html). + +The format module is an optional import. + +```typescript +import { Format } from '@sinclair/typebox/format' +``` + +The following creates a `palindrome` string format. + +```typescript +Format.Set('palindrome', value => value === value.split('').reverse().join('')) +``` + +Once set, this format can then be used by the TypeCompiler and Value modules. + +```typescript +const T = Type.String({ format: 'palindrome' }) + +const A = TypeCompiler.Compile(T).Check('engine') // const A = false + +const B = Value.Check(T, 'kayak') // const B = true +``` + + + +## Benchmark + +This project maintains a set of benchmarks that measure Ajv, Value and TypeCompiler compilation and validation performance. These benchmarks can be run locally by cloning this repository and running `npm run benchmark`. The results below show for Ajv version 8.11.0. + +For additional comparative benchmarks, please refer to [typescript-runtime-type-benchmarks](https://moltar.github.io/typescript-runtime-type-benchmarks/). + + + +### Compile + +This benchmark measures compilation performance for varying types. You can review this benchmark [here](https://github.com/sinclairzx81/typebox/blob/master/benchmark/measurement/module/compile.ts). + +```typescript +┌──────────────────┬────────────┬──────────────┬──────────────┬──────────────┐ +│ (index) │ Iterations │ Ajv │ TypeCompiler │ Performance │ +├──────────────────┼────────────┼──────────────┼──────────────┼──────────────┤ +│ Number │ 2000 │ ' 428 ms' │ ' 12 ms' │ ' 35.67 x' │ +│ String │ 2000 │ ' 337 ms' │ ' 12 ms' │ ' 28.08 x' │ +│ Boolean │ 2000 │ ' 317 ms' │ ' 11 ms' │ ' 28.82 x' │ +│ Null │ 2000 │ ' 274 ms' │ ' 10 ms' │ ' 27.40 x' │ +│ RegEx │ 2000 │ ' 500 ms' │ ' 18 ms' │ ' 27.78 x' │ +│ ObjectA │ 2000 │ ' 2717 ms' │ ' 49 ms' │ ' 55.45 x' │ +│ ObjectB │ 2000 │ ' 2854 ms' │ ' 37 ms' │ ' 77.14 x' │ +│ Tuple │ 2000 │ ' 1224 ms' │ ' 21 ms' │ ' 58.29 x' │ +│ Union │ 2000 │ ' 1266 ms' │ ' 23 ms' │ ' 55.04 x' │ +│ Vector4 │ 2000 │ ' 1513 ms' │ ' 19 ms' │ ' 79.63 x' │ +│ Matrix4 │ 2000 │ ' 841 ms' │ ' 12 ms' │ ' 70.08 x' │ +│ Literal_String │ 2000 │ ' 327 ms' │ ' 8 ms' │ ' 40.88 x' │ +│ Literal_Number │ 2000 │ ' 358 ms' │ ' 6 ms' │ ' 59.67 x' │ +│ Literal_Boolean │ 2000 │ ' 355 ms' │ ' 5 ms' │ ' 71.00 x' │ +│ Array_Number │ 2000 │ ' 685 ms' │ ' 7 ms' │ ' 97.86 x' │ +│ Array_String │ 2000 │ ' 716 ms' │ ' 11 ms' │ ' 65.09 x' │ +│ Array_Boolean │ 2000 │ ' 732 ms' │ ' 6 ms' │ ' 122.00 x' │ +│ Array_ObjectA │ 2000 │ ' 3503 ms' │ ' 34 ms' │ ' 103.03 x' │ +│ Array_ObjectB │ 2000 │ ' 3626 ms' │ ' 38 ms' │ ' 95.42 x' │ +│ Array_Tuple │ 2000 │ ' 2095 ms' │ ' 21 ms' │ ' 99.76 x' │ +│ Array_Union │ 2000 │ ' 1577 ms' │ ' 22 ms' │ ' 71.68 x' │ +│ Array_Vector4 │ 2000 │ ' 2172 ms' │ ' 17 ms' │ ' 127.76 x' │ +│ Array_Matrix4 │ 2000 │ ' 1468 ms' │ ' 19 ms' │ ' 77.26 x' │ +└──────────────────┴────────────┴──────────────┴──────────────┴──────────────┘ +``` + + + +### Validate + +This benchmark measures validation performance for varying types. You can review this benchmark [here](https://github.com/sinclairzx81/typebox/blob/master/benchmark/measurement/module/check.ts). + +```typescript +┌──────────────────┬────────────┬──────────────┬──────────────┬──────────────┬──────────────┐ +│ (index) │ Iterations │ ValueCheck │ Ajv │ TypeCompiler │ Performance │ +├──────────────────┼────────────┼──────────────┼──────────────┼──────────────┼──────────────┤ +│ Number │ 1000000 │ ' 24 ms' │ ' 9 ms' │ ' 6 ms' │ ' 1.50 x' │ +│ String │ 1000000 │ ' 23 ms' │ ' 19 ms' │ ' 12 ms' │ ' 1.58 x' │ +│ Boolean │ 1000000 │ ' 24 ms' │ ' 19 ms' │ ' 10 ms' │ ' 1.90 x' │ +│ Null │ 1000000 │ ' 23 ms' │ ' 18 ms' │ ' 9 ms' │ ' 2.00 x' │ +│ RegEx │ 1000000 │ ' 164 ms' │ ' 46 ms' │ ' 38 ms' │ ' 1.21 x' │ +│ ObjectA │ 1000000 │ ' 548 ms' │ ' 36 ms' │ ' 22 ms' │ ' 1.64 x' │ +│ ObjectB │ 1000000 │ ' 1118 ms' │ ' 51 ms' │ ' 38 ms' │ ' 1.34 x' │ +│ Tuple │ 1000000 │ ' 136 ms' │ ' 25 ms' │ ' 14 ms' │ ' 1.79 x' │ +│ Union │ 1000000 │ ' 338 ms' │ ' 27 ms' │ ' 16 ms' │ ' 1.69 x' │ +│ Recursive │ 1000000 │ ' 3251 ms' │ ' 416 ms' │ ' 98 ms' │ ' 4.24 x' │ +│ Vector4 │ 1000000 │ ' 146 ms' │ ' 23 ms' │ ' 12 ms' │ ' 1.92 x' │ +│ Matrix4 │ 1000000 │ ' 584 ms' │ ' 40 ms' │ ' 25 ms' │ ' 1.60 x' │ +│ Literal_String │ 1000000 │ ' 46 ms' │ ' 19 ms' │ ' 10 ms' │ ' 1.90 x' │ +│ Literal_Number │ 1000000 │ ' 46 ms' │ ' 20 ms' │ ' 10 ms' │ ' 2.00 x' │ +│ Literal_Boolean │ 1000000 │ ' 47 ms' │ ' 21 ms' │ ' 10 ms' │ ' 2.10 x' │ +│ Array_Number │ 1000000 │ ' 456 ms' │ ' 31 ms' │ ' 19 ms' │ ' 1.63 x' │ +│ Array_String │ 1000000 │ ' 489 ms' │ ' 40 ms' │ ' 25 ms' │ ' 1.60 x' │ +│ Array_Boolean │ 1000000 │ ' 458 ms' │ ' 35 ms' │ ' 27 ms' │ ' 1.30 x' │ +│ Array_ObjectA │ 1000000 │ ' 13559 ms' │ ' 2568 ms' │ ' 1564 ms' │ ' 1.64 x' │ +│ Array_ObjectB │ 1000000 │ ' 15863 ms' │ ' 2744 ms' │ ' 2060 ms' │ ' 1.33 x' │ +│ Array_Tuple │ 1000000 │ ' 1694 ms' │ ' 96 ms' │ ' 63 ms' │ ' 1.52 x' │ +│ Array_Union │ 1000000 │ ' 4736 ms' │ ' 229 ms' │ ' 86 ms' │ ' 2.66 x' │ +│ Array_Recursive │ 1000000 │ ' 53804 ms' │ ' 6744 ms' │ ' 1167 ms' │ ' 5.78 x' │ +│ Array_Vector4 │ 1000000 │ ' 2244 ms' │ ' 99 ms' │ ' 46 ms' │ ' 2.15 x' │ +│ Array_Matrix4 │ 1000000 │ ' 11966 ms' │ ' 378 ms' │ ' 229 ms' │ ' 1.65 x' │ +└──────────────────┴────────────┴──────────────┴──────────────┴──────────────┴──────────────┘ +``` + + + +### Compression + +The following table lists esbuild compiled and minified sizes for each TypeBox module. + +```typescript +┌──────────────────────┬────────────┬────────────┬─────────────┐ +│ (index) │ Compiled │ Minified │ Compression │ +├──────────────────────┼────────────┼────────────┼─────────────┤ +│ typebox/compiler │ ' 51 kb' │ ' 25 kb' │ '2.00 x' │ +│ typebox/conditional │ ' 42 kb' │ ' 17 kb' │ '2.46 x' │ +│ typebox/format │ ' 0 kb' │ ' 0 kb' │ '2.66 x' │ +│ typebox/guard │ ' 21 kb' │ ' 10 kb' │ '2.08 x' │ +│ typebox/value │ ' 74 kb' │ ' 34 kb' │ '2.16 x' │ +│ typebox │ ' 11 kb' │ ' 6 kb' │ '1.91 x' │ +└──────────────────────┴────────────┴────────────┴─────────────┘ +``` + + + +## Contribute + +TypeBox is open to community contribution. Please ensure you submit an open issue before submitting your pull request. The TypeBox project preferences open community discussion prior to accepting new features. diff --git a/node_modules/@sinclair/typebox/typebox.d.ts b/node_modules/@sinclair/typebox/typebox.d.ts new file mode 100644 index 0000000..0ace42a --- /dev/null +++ b/node_modules/@sinclair/typebox/typebox.d.ts @@ -0,0 +1,408 @@ +export declare const Kind: unique symbol; +export declare const Hint: unique symbol; +export declare const Modifier: unique symbol; +export declare type TModifier = TReadonlyOptional | TOptional | TReadonly; +export declare type TReadonly = T & { + [Modifier]: 'Readonly'; +}; +export declare type TOptional = T & { + [Modifier]: 'Optional'; +}; +export declare type TReadonlyOptional = T & { + [Modifier]: 'ReadonlyOptional'; +}; +export interface SchemaOptions { + $schema?: string; + /** Id for this schema */ + $id?: string; + /** Title of this schema */ + title?: string; + /** Description of this schema */ + description?: string; + /** Default value for this schema */ + default?: any; + /** Example values matching this schema. */ + examples?: any; + [prop: string]: any; +} +export interface TSchema extends SchemaOptions { + [Kind]: string; + [Hint]?: string; + [Modifier]?: string; + params: unknown[]; + static: unknown; +} +export declare type TAnySchema = TSchema | TAny | TArray | TBoolean | TConstructor | TEnum | TFunction | TInteger | TLiteral | TNull | TNumber | TObject | TPromise | TRecord | TSelf | TRef | TString | TTuple | TUndefined | TUnion | TUint8Array | TUnknown | TVoid; +export interface NumericOptions extends SchemaOptions { + exclusiveMaximum?: number; + exclusiveMinimum?: number; + maximum?: number; + minimum?: number; + multipleOf?: number; +} +export declare type TNumeric = TInteger | TNumber; +export interface TAny extends TSchema { + [Kind]: 'Any'; + static: any; +} +export interface ArrayOptions extends SchemaOptions { + uniqueItems?: boolean; + minItems?: number; + maxItems?: number; +} +export interface TArray extends TSchema, ArrayOptions { + [Kind]: 'Array'; + static: Array>; + type: 'array'; + items: T; +} +export interface TBoolean extends TSchema { + [Kind]: 'Boolean'; + static: boolean; + type: 'boolean'; +} +export declare type TConstructorParameters> = TTuple; +export declare type TInstanceType> = T['returns']; +export declare type StaticContructorParameters = [...{ + [K in keyof T]: T[K] extends TSchema ? Static : never; +}]; +export interface TConstructor extends TSchema { + [Kind]: 'Constructor'; + static: new (...param: StaticContructorParameters) => Static; + type: 'constructor'; + parameters: T; + returns: U; +} +export interface TEnumOption { + type: 'number' | 'string'; + const: T; +} +export interface TEnum = Record> extends TSchema { + [Kind]: 'Union'; + static: T[keyof T]; + anyOf: TLiteral[]; +} +export declare type TParameters = TTuple; +export declare type TReturnType = T['returns']; +export declare type StaticFunctionParameters = [...{ + [K in keyof T]: T[K] extends TSchema ? Static : never; +}]; +export interface TFunction extends TSchema { + [Kind]: 'Function'; + static: (...param: StaticFunctionParameters) => Static; + type: 'function'; + parameters: T; + returns: U; +} +export interface TInteger extends TSchema, NumericOptions { + [Kind]: 'Integer'; + static: number; + type: 'integer'; +} +export declare type IntersectReduce = T extends [infer A, ...infer B] ? IntersectReduce : I extends object ? I : {}; +export declare type IntersectEvaluate = { + [K in keyof T]: T[K] extends TSchema ? Static : never; +}; +export declare type IntersectProperties = { + [K in keyof T]: T[K] extends TObject ? P : {}; +}; +export interface TIntersect extends TObject { + static: IntersectReduce>; + properties: IntersectReduce>; +} +export declare type UnionToIntersect = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never; +export declare type UnionLast = UnionToIntersect 0 : never> extends (x: infer L) => 0 ? L : never; +export declare type UnionToTuple> = [U] extends [never] ? [] : [...UnionToTuple>, L]; +export declare type UnionStringLiteralToTuple = T extends TUnion ? { + [I in keyof L]: L[I] extends TLiteral ? C : never; +} : never; +export declare type UnionLiteralsFromObject = { + [K in ObjectPropertyKeys]: TLiteral; +} extends infer R ? UnionToTuple : never; +export interface TKeyOf extends TUnion> { +} +export declare type TLiteralValue = string | number | boolean; +export interface TLiteral extends TSchema { + [Kind]: 'Literal'; + static: T; + const: T; +} +export interface TNever extends TSchema { + [Kind]: 'Never'; + static: never; + allOf: [{ + type: 'boolean'; + const: false; + }, { + type: 'boolean'; + const: true; + }]; +} +export interface TNull extends TSchema { + [Kind]: 'Null'; + static: null; + type: 'null'; +} +export interface TNumber extends TSchema, NumericOptions { + [Kind]: 'Number'; + static: number; + type: 'number'; +} +export declare type ReadonlyOptionalPropertyKeys = { + [K in keyof T]: T[K] extends TReadonlyOptional ? K : never; +}[keyof T]; +export declare type ReadonlyPropertyKeys = { + [K in keyof T]: T[K] extends TReadonly ? K : never; +}[keyof T]; +export declare type OptionalPropertyKeys = { + [K in keyof T]: T[K] extends TOptional ? K : never; +}[keyof T]; +export declare type RequiredPropertyKeys = keyof Omit | ReadonlyPropertyKeys | OptionalPropertyKeys>; +export declare type PropertiesReduce = { + readonly [K in ReadonlyOptionalPropertyKeys]?: Static; +} & { + readonly [K in ReadonlyPropertyKeys]: Static; +} & { + [K in OptionalPropertyKeys]?: Static; +} & { + [K in RequiredPropertyKeys]: Static; +} extends infer R ? { + [K in keyof R]: R[K]; +} : never; +export declare type TRecordProperties, T extends TSchema> = Static extends string ? { + [X in Static]: T; +} : never; +export interface TProperties { + [key: string]: TSchema; +} +export declare type ObjectProperties = T extends TObject ? U : never; +export declare type ObjectPropertyKeys = T extends TObject ? keyof U : never; +export declare type TAdditionalProperties = undefined | TSchema | boolean; +export interface ObjectOptions extends SchemaOptions { + additionalProperties?: TAdditionalProperties; + minProperties?: number; + maxProperties?: number; +} +export interface TObject extends TSchema, ObjectOptions { + [Kind]: 'Object'; + static: PropertiesReduce; + additionalProperties?: TAdditionalProperties; + type: 'object'; + properties: T; + required?: string[]; +} +export interface TOmit[]> extends TObject, ObjectOptions { + static: Omit, Properties[number]>; + properties: T extends TObject ? Omit : never; +} +export interface TPartial extends TObject { + static: Partial>; + properties: { + [K in keyof T['properties']]: T['properties'][K] extends TReadonlyOptional ? TReadonlyOptional : T['properties'][K] extends TReadonly ? TReadonlyOptional : T['properties'][K] extends TOptional ? TOptional : TOptional; + }; +} +export declare type TPick[]> = TObject<{ + [K in Properties[number]]: T['properties'][K]; +}>; +export interface TPromise extends TSchema { + [Kind]: 'Promise'; + static: Promise>; + type: 'promise'; + item: TSchema; +} +export declare type TRecordKey = TString | TNumeric | TUnion[]>; +export interface TRecord extends TSchema { + [Kind]: 'Record'; + static: Record, Static>; + type: 'object'; + patternProperties: { + [pattern: string]: T; + }; + additionalProperties: false; +} +export interface TSelf extends TSchema { + [Kind]: 'Self'; + static: this['params'][0]; + $ref: string; +} +export declare type TRecursiveReduce = Static]>; +export interface TRecursive extends TSchema { + static: TRecursiveReduce; +} +export interface TRef extends TSchema { + [Kind]: 'Ref'; + static: Static; + $ref: string; +} +export interface TRequired> extends TObject { + static: Required>; + properties: { + [K in keyof T['properties']]: T['properties'][K] extends TReadonlyOptional ? TReadonly : T['properties'][K] extends TReadonly ? TReadonly : T['properties'][K] extends TOptional ? U : T['properties'][K]; + }; +} +export declare type StringFormatOption = 'date-time' | 'time' | 'date' | 'email' | 'idn-email' | 'hostname' | 'idn-hostname' | 'ipv4' | 'ipv6' | 'uri' | 'uri-reference' | 'iri' | 'uuid' | 'iri-reference' | 'uri-template' | 'json-pointer' | 'relative-json-pointer' | 'regex'; +export interface StringOptions extends SchemaOptions { + minLength?: number; + maxLength?: number; + pattern?: string; + format?: Format; + contentEncoding?: '7bit' | '8bit' | 'binary' | 'quoted-printable' | 'base64'; + contentMediaType?: string; +} +export interface TString extends TSchema, StringOptions { + [Kind]: 'String'; + static: string; + type: 'string'; +} +export declare type TupleToArray> = T extends TTuple ? R : never; +export interface TTuple extends TSchema { + [Kind]: 'Tuple'; + static: { + [K in keyof T]: T[K] extends TSchema ? Static : T[K]; + }; + type: 'array'; + items?: T; + additionalItems?: false; + minItems: number; + maxItems: number; +} +export interface TUndefined extends TSchema { + [Kind]: 'Undefined'; + specialized: 'Undefined'; + static: undefined; + type: 'object'; +} +export interface TUnion extends TSchema { + [Kind]: 'Union'; + static: { + [K in keyof T]: T[K] extends TSchema ? Static : never; + }[number]; + anyOf: T; +} +export interface Uint8ArrayOptions extends SchemaOptions { + maxByteLength?: number; + minByteLength?: number; +} +export interface TUint8Array extends TSchema, Uint8ArrayOptions { + [Kind]: 'Uint8Array'; + static: Uint8Array; + specialized: 'Uint8Array'; + type: 'object'; +} +export interface TUnknown extends TSchema { + [Kind]: 'Unknown'; + static: unknown; +} +export interface UnsafeOptions extends SchemaOptions { + [Kind]?: string; +} +export interface TUnsafe extends TSchema { + [Kind]: string; + static: T; +} +export interface TVoid extends TSchema { + [Kind]: 'Void'; + static: void; + type: 'null'; +} +/** Creates a static type from a TypeBox type */ +export declare type Static = (T & { + params: P; +})['static']; +export declare class TypeBuilder { + /** Creates a readonly optional property */ + ReadonlyOptional(item: T): TReadonlyOptional; + /** Creates a readonly property */ + Readonly(item: T): TReadonly; + /** Creates a optional property */ + Optional(item: T): TOptional; + /** Creates a any type */ + Any(options?: SchemaOptions): TAny; + /** Creates a array type */ + Array(items: T, options?: ArrayOptions): TArray; + /** Creates a boolean type */ + Boolean(options?: SchemaOptions): TBoolean; + /** Creates a tuple type from this constructors parameters */ + ConstructorParameters>(schema: T, options?: SchemaOptions): TConstructorParameters; + /** Creates a constructor type */ + Constructor, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TConstructor, U>; + /** Creates a constructor type */ + Constructor(parameters: [...T], returns: U, options?: SchemaOptions): TConstructor; + /** Creates a enum type */ + Enum>(item: T, options?: SchemaOptions): TEnum; + /** Creates a function type */ + Function, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TFunction, U>; + /** Creates a function type */ + Function(parameters: [...T], returns: U, options?: SchemaOptions): TFunction; + /** Creates a type from this constructors instance type */ + InstanceType>(schema: T, options?: SchemaOptions): TInstanceType; + /** Creates a integer type */ + Integer(options?: NumericOptions): TInteger; + /** Creates a intersect type. */ + Intersect(objects: [...T], options?: ObjectOptions): TIntersect; + /** Creates a keyof type */ + KeyOf(object: T, options?: SchemaOptions): TKeyOf; + /** Creates a literal type. */ + Literal(value: T, options?: SchemaOptions): TLiteral; + /** Creates a never type */ + Never(options?: SchemaOptions): TNever; + /** Creates a null type */ + Null(options?: SchemaOptions): TNull; + /** Creates a number type */ + Number(options?: NumericOptions): TNumber; + /** Creates an object type with the given properties */ + Object(properties: T, options?: ObjectOptions): TObject; + /** Creates a new object whose properties are omitted from the given object */ + Omit[]>>(schema: T, keys: K, options?: ObjectOptions): TOmit>; + /** Creates a new object whose properties are omitted from the given object */ + Omit[]>(schema: T, keys: readonly [...K], options?: ObjectOptions): TOmit; + /** Creates a tuple type from this functions parameters */ + Parameters>(schema: T, options?: SchemaOptions): TParameters; + /** Creates an object type whose properties are all optional */ + Partial(schema: T, options?: ObjectOptions): TPartial; + /** Creates a object whose properties are picked from the given object */ + Pick[]>>(schema: T, keys: K, options?: ObjectOptions): TPick>; + /** Creates a object whose properties are picked from the given object */ + Pick[]>(schema: T, keys: readonly [...K], options?: ObjectOptions): TPick; + /** Creates a promise type. This type cannot be represented in schema. */ + Promise(item: T, options?: SchemaOptions): TPromise; + /** Creates an object whose properties are derived from the given string literal union. */ + Record, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): TObject>; + /** Creates a record type */ + Record(key: K, schema: T, options?: ObjectOptions): TRecord; + /** Creates a recursive object type */ + Recursive(callback: (self: TSelf) => T, options?: SchemaOptions): TRecursive; + /** Creates a reference schema */ + Ref(schema: T, options?: SchemaOptions): TRef; + /** Creates a string type from a regular expression */ + RegEx(regex: RegExp, options?: SchemaOptions): TString; + /** Creates an object type whose properties are all required */ + Required(schema: T, options?: SchemaOptions): TRequired; + /** Creates a type from this functions return type */ + ReturnType>(schema: T, options?: SchemaOptions): TReturnType; + /** Removes Kind and Modifier symbol property keys from this schema */ + Strict(schema: T): T; + /** Creates a string type */ + String(options?: StringOptions): TString; + /** Creates a tuple type */ + Tuple(items: [...T], options?: SchemaOptions): TTuple; + /** Creates a undefined type */ + Undefined(options?: SchemaOptions): TUndefined; + /** Creates a union type */ + Union(items: [], options?: SchemaOptions): TNever; + Union(items: [...T], options?: SchemaOptions): TUnion; + /** Creates a Uint8Array type */ + Uint8Array(options?: Uint8ArrayOptions): TUint8Array; + /** Creates an unknown type */ + Unknown(options?: SchemaOptions): TUnknown; + /** Creates a user defined schema that infers as type T */ + Unsafe(options?: UnsafeOptions): TUnsafe; + /** Creates a void type */ + Void(options?: SchemaOptions): TVoid; + /** Use this function to return TSchema with static and params omitted */ + protected Create(schema: Omit): T; + /** Clones the given value */ + protected Clone(value: any): any; +} +/** JSON Schema Type Builder with Static Type Resolution for TypeScript */ +export declare const Type: TypeBuilder; diff --git a/node_modules/@sinclair/typebox/typebox.js b/node_modules/@sinclair/typebox/typebox.js new file mode 100644 index 0000000..9856390 --- /dev/null +++ b/node_modules/@sinclair/typebox/typebox.js @@ -0,0 +1,383 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.Type = exports.TypeBuilder = exports.Modifier = exports.Hint = exports.Kind = void 0; +// -------------------------------------------------------------------------- +// Symbols +// -------------------------------------------------------------------------- +exports.Kind = Symbol.for('TypeBox.Kind'); +exports.Hint = Symbol.for('TypeBox.Hint'); +exports.Modifier = Symbol.for('TypeBox.Modifier'); +// -------------------------------------------------------------------------- +// TypeBuilder +// -------------------------------------------------------------------------- +let TypeOrdinal = 0; +class TypeBuilder { + // ---------------------------------------------------------------------- + // Modifiers + // ---------------------------------------------------------------------- + /** Creates a readonly optional property */ + ReadonlyOptional(item) { + return { [exports.Modifier]: 'ReadonlyOptional', ...item }; + } + /** Creates a readonly property */ + Readonly(item) { + return { [exports.Modifier]: 'Readonly', ...item }; + } + /** Creates a optional property */ + Optional(item) { + return { [exports.Modifier]: 'Optional', ...item }; + } + // ---------------------------------------------------------------------- + // Types + // ---------------------------------------------------------------------- + /** Creates a any type */ + Any(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Any' }); + } + /** Creates a array type */ + Array(items, options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Array', type: 'array', items }); + } + /** Creates a boolean type */ + Boolean(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Boolean', type: 'boolean' }); + } + /** Creates a tuple type from this constructors parameters */ + ConstructorParameters(schema, options = {}) { + return this.Tuple([...schema.parameters], { ...options }); + } + /** Creates a constructor type */ + Constructor(parameters, returns, options = {}) { + if (parameters[exports.Kind] === 'Tuple') { + const inner = parameters.items === undefined ? [] : parameters.items; + return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'constructor', parameters: inner, returns }); + } + else if (globalThis.Array.isArray(parameters)) { + return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'constructor', parameters, returns }); + } + else { + throw new Error('TypeBuilder.Constructor: Invalid parameters'); + } + } + /** Creates a enum type */ + Enum(item, options = {}) { + const values = Object.keys(item) + .filter((key) => isNaN(key)) + .map((key) => item[key]); + const anyOf = values.map((value) => (typeof value === 'string' ? { [exports.Kind]: 'Literal', type: 'string', const: value } : { [exports.Kind]: 'Literal', type: 'number', const: value })); + return this.Create({ ...options, [exports.Kind]: 'Union', [exports.Hint]: 'Enum', anyOf }); + } + /** Creates a function type */ + Function(parameters, returns, options = {}) { + if (parameters[exports.Kind] === 'Tuple') { + const inner = parameters.items === undefined ? [] : parameters.items; + return this.Create({ ...options, [exports.Kind]: 'Function', type: 'function', parameters: inner, returns }); + } + else if (globalThis.Array.isArray(parameters)) { + return this.Create({ ...options, [exports.Kind]: 'Function', type: 'function', parameters, returns }); + } + else { + throw new Error('TypeBuilder.Function: Invalid parameters'); + } + } + /** Creates a type from this constructors instance type */ + InstanceType(schema, options = {}) { + return { ...options, ...this.Clone(schema.returns) }; + } + /** Creates a integer type */ + Integer(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Integer', type: 'integer' }); + } + /** Creates a intersect type. */ + Intersect(objects, options = {}) { + const isOptional = (schema) => (schema[exports.Modifier] && schema[exports.Modifier] === 'Optional') || schema[exports.Modifier] === 'ReadonlyOptional'; + const [required, optional] = [new Set(), new Set()]; + for (const object of objects) { + for (const [key, schema] of Object.entries(object.properties)) { + if (isOptional(schema)) + optional.add(key); + } + } + for (const object of objects) { + for (const key of Object.keys(object.properties)) { + if (!optional.has(key)) + required.add(key); + } + } + const properties = {}; + for (const object of objects) { + for (const [key, schema] of Object.entries(object.properties)) { + properties[key] = properties[key] === undefined ? schema : { [exports.Kind]: 'Union', anyOf: [properties[key], { ...schema }] }; + } + } + if (required.size > 0) { + return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties, required: [...required] }); + } + else { + return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties }); + } + } + /** Creates a keyof type */ + KeyOf(object, options = {}) { + const items = Object.keys(object.properties).map((key) => this.Create({ ...options, [exports.Kind]: 'Literal', type: 'string', const: key })); + return this.Create({ ...options, [exports.Kind]: 'Union', [exports.Hint]: 'KeyOf', anyOf: items }); + } + /** Creates a literal type. */ + Literal(value, options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Literal', const: value, type: typeof value }); + } + /** Creates a never type */ + Never(options = {}) { + return this.Create({ + ...options, + [exports.Kind]: 'Never', + allOf: [ + { type: 'boolean', const: false }, + { type: 'boolean', const: true }, + ], + }); + } + /** Creates a null type */ + Null(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Null', type: 'null' }); + } + /** Creates a number type */ + Number(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Number', type: 'number' }); + } + /** Creates an object type with the given properties */ + Object(properties, options = {}) { + const property_names = Object.keys(properties); + const optional = property_names.filter((name) => { + const property = properties[name]; + const modifier = property[exports.Modifier]; + return modifier && (modifier === 'Optional' || modifier === 'ReadonlyOptional'); + }); + const required = property_names.filter((name) => !optional.includes(name)); + if (required.length > 0) { + return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties, required }); + } + else { + return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties }); + } + } + /** Creates a new object whose properties are omitted from the given object */ + Omit(schema, keys, options = {}) { + const select = keys[exports.Kind] === 'Union' ? keys.anyOf.map((schema) => schema.const) : keys; + const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Omit' }; + if (next.required) { + next.required = next.required.filter((key) => !select.includes(key)); + if (next.required.length === 0) + delete next.required; + } + for (const key of Object.keys(next.properties)) { + if (select.includes(key)) + delete next.properties[key]; + } + return this.Create(next); + } + /** Creates a tuple type from this functions parameters */ + Parameters(schema, options = {}) { + return exports.Type.Tuple(schema.parameters, { ...options }); + } + /** Creates an object type whose properties are all optional */ + Partial(schema, options = {}) { + const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Partial' }; + delete next.required; + for (const key of Object.keys(next.properties)) { + const property = next.properties[key]; + const modifer = property[exports.Modifier]; + switch (modifer) { + case 'ReadonlyOptional': + property[exports.Modifier] = 'ReadonlyOptional'; + break; + case 'Readonly': + property[exports.Modifier] = 'ReadonlyOptional'; + break; + case 'Optional': + property[exports.Modifier] = 'Optional'; + break; + default: + property[exports.Modifier] = 'Optional'; + break; + } + } + return this.Create(next); + } + /** Creates a object whose properties are picked from the given object */ + Pick(schema, keys, options = {}) { + const select = keys[exports.Kind] === 'Union' ? keys.anyOf.map((schema) => schema.const) : keys; + const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Pick' }; + if (next.required) { + next.required = next.required.filter((key) => select.includes(key)); + if (next.required.length === 0) + delete next.required; + } + for (const key of Object.keys(next.properties)) { + if (!select.includes(key)) + delete next.properties[key]; + } + return this.Create(next); + } + /** Creates a promise type. This type cannot be represented in schema. */ + Promise(item, options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Promise', type: 'promise', item }); + } + /** Creates a record type */ + Record(key, value, options = {}) { + // If string literal union return TObject with properties extracted from union. + if (key[exports.Kind] === 'Union') { + return this.Object(key.anyOf.reduce((acc, literal) => { + return { ...acc, [literal.const]: value }; + }, {}), { ...options, [exports.Hint]: 'Record' }); + } + // otherwise return TRecord with patternProperties + const pattern = ['Integer', 'Number'].includes(key[exports.Kind]) ? '^(0|[1-9][0-9]*)$' : key[exports.Kind] === 'String' && key.pattern ? key.pattern : '^.*$'; + return this.Create({ + ...options, + [exports.Kind]: 'Record', + type: 'object', + patternProperties: { [pattern]: value }, + additionalProperties: false, + }); + } + /** Creates a recursive object type */ + Recursive(callback, options = {}) { + if (options.$id === undefined) + options.$id = `T${TypeOrdinal++}`; + const self = callback({ [exports.Kind]: 'Self', $ref: `${options.$id}` }); + self.$id = options.$id; + return this.Create({ ...options, ...self }); + } + /** Creates a reference schema */ + Ref(schema, options = {}) { + if (schema.$id === undefined) + throw Error('TypeBuilder.Ref: Referenced schema must specify an $id'); + return this.Create({ ...options, [exports.Kind]: 'Ref', $ref: schema.$id }); + } + /** Creates a string type from a regular expression */ + RegEx(regex, options = {}) { + return this.Create({ ...options, [exports.Kind]: 'String', type: 'string', pattern: regex.source }); + } + /** Creates an object type whose properties are all required */ + Required(schema, options = {}) { + const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Required' }; + next.required = Object.keys(next.properties); + for (const key of Object.keys(next.properties)) { + const property = next.properties[key]; + const modifier = property[exports.Modifier]; + switch (modifier) { + case 'ReadonlyOptional': + property[exports.Modifier] = 'Readonly'; + break; + case 'Readonly': + property[exports.Modifier] = 'Readonly'; + break; + case 'Optional': + delete property[exports.Modifier]; + break; + default: + delete property[exports.Modifier]; + break; + } + } + return this.Create(next); + } + /** Creates a type from this functions return type */ + ReturnType(schema, options = {}) { + return { ...options, ...this.Clone(schema.returns) }; + } + /** Removes Kind and Modifier symbol property keys from this schema */ + Strict(schema) { + return JSON.parse(JSON.stringify(schema)); + } + /** Creates a string type */ + String(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'String', type: 'string' }); + } + /** Creates a tuple type */ + Tuple(items, options = {}) { + const additionalItems = false; + const minItems = items.length; + const maxItems = items.length; + const schema = (items.length > 0 ? { ...options, [exports.Kind]: 'Tuple', type: 'array', items, additionalItems, minItems, maxItems } : { ...options, [exports.Kind]: 'Tuple', type: 'array', minItems, maxItems }); + return this.Create(schema); + } + /** Creates a undefined type */ + Undefined(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Undefined', type: 'object', specialized: 'Undefined' }); + } + Union(items, options = {}) { + return items.length === 0 ? exports.Type.Never({ ...options }) : this.Create({ ...options, [exports.Kind]: 'Union', anyOf: items }); + } + /** Creates a Uint8Array type */ + Uint8Array(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Uint8Array', type: 'object', specialized: 'Uint8Array' }); + } + /** Creates an unknown type */ + Unknown(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Unknown' }); + } + /** Creates a user defined schema that infers as type T */ + Unsafe(options = {}) { + return this.Create({ ...options, [exports.Kind]: options[exports.Kind] || 'Unsafe' }); + } + /** Creates a void type */ + Void(options = {}) { + return this.Create({ ...options, [exports.Kind]: 'Void', type: 'null' }); + } + /** Use this function to return TSchema with static and params omitted */ + Create(schema) { + return schema; + } + /** Clones the given value */ + Clone(value) { + const isObject = (object) => typeof object === 'object' && object !== null && !Array.isArray(object); + const isArray = (object) => typeof object === 'object' && object !== null && Array.isArray(object); + if (isObject(value)) { + return Object.keys(value).reduce((acc, key) => ({ + ...acc, + [key]: this.Clone(value[key]), + }), Object.getOwnPropertySymbols(value).reduce((acc, key) => ({ + ...acc, + [key]: this.Clone(value[key]), + }), {})); + } + else if (isArray(value)) { + return value.map((item) => this.Clone(item)); + } + else { + return value; + } + } +} +exports.TypeBuilder = TypeBuilder; +/** JSON Schema Type Builder with Static Type Resolution for TypeScript */ +exports.Type = new TypeBuilder(); diff --git a/node_modules/@sinclair/typebox/value/cast.d.ts b/node_modules/@sinclair/typebox/value/cast.d.ts new file mode 100644 index 0000000..0ab8ef6 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/cast.d.ts @@ -0,0 +1,26 @@ +import * as Types from '../typebox'; +export declare class ValueCastReferenceTypeError extends Error { + readonly schema: Types.TRef | Types.TSelf; + constructor(schema: Types.TRef | Types.TSelf); +} +export declare class ValueCastArrayUniqueItemsTypeError extends Error { + readonly schema: Types.TSchema; + readonly value: unknown; + constructor(schema: Types.TSchema, value: unknown); +} +export declare class ValueCastNeverTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueCastRecursiveTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueCastUnknownTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare namespace ValueCast { + function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): any; + function Cast(schema: T, references: [...R], value: any): Types.Static; +} diff --git a/node_modules/@sinclair/typebox/value/cast.js b/node_modules/@sinclair/typebox/value/cast.js new file mode 100644 index 0000000..f04e2d6 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/cast.js @@ -0,0 +1,364 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.ValueCast = exports.ValueCastUnknownTypeError = exports.ValueCastRecursiveTypeError = exports.ValueCastNeverTypeError = exports.ValueCastArrayUniqueItemsTypeError = exports.ValueCastReferenceTypeError = void 0; +const Types = require("../typebox"); +const create_1 = require("./create"); +const check_1 = require("./check"); +const clone_1 = require("./clone"); +var UnionValueCast; +(function (UnionValueCast) { + // ---------------------------------------------------------------------------------------------- + // The following will score a schema against a value. For objects, the score is the tally of + // points awarded for each property of the value. Property points are (1.0 / propertyCount) + // to prevent large property counts biasing results. Properties that match literal values are + // maximally awarded as literals are typically used as union discriminator fields. + // ---------------------------------------------------------------------------------------------- + function Score(schema, references, value) { + if (schema[Types.Kind] === 'Object' && typeof value === 'object' && value !== null) { + const object = schema; + const keys = Object.keys(value); + const entries = globalThis.Object.entries(object.properties); + const [point, max] = [1 / entries.length, entries.length]; + return entries.reduce((acc, [key, schema]) => { + const literal = schema[Types.Kind] === 'Literal' && schema.const === value[key] ? max : 0; + const checks = check_1.ValueCheck.Check(schema, references, value[key]) ? point : 0; + const exists = keys.includes(key) ? point : 0; + return acc + (literal + checks + exists); + }, 0); + } + else { + return check_1.ValueCheck.Check(schema, references, value) ? 1 : 0; + } + } + function Select(union, references, value) { + let [select, best] = [union.anyOf[0], 0]; + for (const schema of union.anyOf) { + const score = Score(schema, references, value); + if (score > best) { + select = schema; + best = score; + } + } + return select; + } + function Create(union, references, value) { + return check_1.ValueCheck.Check(union, references, value) ? clone_1.ValueClone.Clone(value) : ValueCast.Cast(Select(union, references, value), references, value); + } + UnionValueCast.Create = Create; +})(UnionValueCast || (UnionValueCast = {})); +// ----------------------------------------------------------- +// Errors +// ----------------------------------------------------------- +class ValueCastReferenceTypeError extends Error { + constructor(schema) { + super(`ValueCast: Cannot locate referenced schema with $id '${schema.$ref}'`); + this.schema = schema; + } +} +exports.ValueCastReferenceTypeError = ValueCastReferenceTypeError; +class ValueCastArrayUniqueItemsTypeError extends Error { + constructor(schema, value) { + super('ValueCast: Array cast produced invalid data due to uniqueItems constraint'); + this.schema = schema; + this.value = value; + } +} +exports.ValueCastArrayUniqueItemsTypeError = ValueCastArrayUniqueItemsTypeError; +class ValueCastNeverTypeError extends Error { + constructor(schema) { + super('ValueCast: Never types cannot be cast'); + this.schema = schema; + } +} +exports.ValueCastNeverTypeError = ValueCastNeverTypeError; +class ValueCastRecursiveTypeError extends Error { + constructor(schema) { + super('ValueCast.Recursive: Cannot cast recursive schemas'); + this.schema = schema; + } +} +exports.ValueCastRecursiveTypeError = ValueCastRecursiveTypeError; +class ValueCastUnknownTypeError extends Error { + constructor(schema) { + super('ValueCast: Unknown type'); + this.schema = schema; + } +} +exports.ValueCastUnknownTypeError = ValueCastUnknownTypeError; +var ValueCast; +(function (ValueCast) { + // ----------------------------------------------------------- + // Guards + // ----------------------------------------------------------- + function IsArray(value) { + return typeof value === 'object' && globalThis.Array.isArray(value); + } + function IsString(value) { + return typeof value === 'string'; + } + function IsBoolean(value) { + return typeof value === 'boolean'; + } + function IsBigInt(value) { + return typeof value === 'bigint'; + } + function IsNumber(value) { + return typeof value === 'number'; + } + function IsStringNumeric(value) { + return IsString(value) && !isNaN(value) && !isNaN(parseFloat(value)); + } + function IsValueToString(value) { + return IsBigInt(value) || IsBoolean(value) || IsNumber(value); + } + function IsValueTrue(value) { + return value === true || (IsNumber(value) && value === 1) || (IsBigInt(value) && value === 1n) || (IsString(value) && (value.toLowerCase() === 'true' || value === '1')); + } + function IsValueFalse(value) { + return value === false || (IsNumber(value) && value === 0) || (IsBigInt(value) && value === 0n) || (IsString(value) && (value.toLowerCase() === 'false' || value === '0')); + } + // ----------------------------------------------------------- + // Convert + // ----------------------------------------------------------- + function TryConvertString(value) { + return IsValueToString(value) ? value.toString() : value; + } + function TryConvertNumber(value) { + return IsStringNumeric(value) ? parseFloat(value) : IsValueTrue(value) ? 1 : value; + } + function TryConvertInteger(value) { + return IsStringNumeric(value) ? parseInt(value) : IsValueTrue(value) ? 1 : value; + } + function TryConvertBoolean(value) { + return IsValueTrue(value) ? true : IsValueFalse(value) ? false : value; + } + // ----------------------------------------------------------- + // Cast + // ----------------------------------------------------------- + function Any(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Array(schema, references, value) { + if (check_1.ValueCheck.Check(schema, references, value)) + return clone_1.ValueClone.Clone(value); + const created = IsArray(value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); + const minimum = IsNumber(schema.minItems) && created.length < schema.minItems ? [...created, ...globalThis.Array.from({ length: schema.minItems - created.length }, () => null)] : created; + const maximum = IsNumber(schema.maxItems) && minimum.length > schema.maxItems ? minimum.slice(0, schema.maxItems) : minimum; + const casted = maximum.map((value) => Visit(schema.items, references, value)); + if (schema.uniqueItems !== true) + return casted; + const unique = [...new Set(casted)]; + if (!check_1.ValueCheck.Check(schema, references, unique)) + throw new ValueCastArrayUniqueItemsTypeError(schema, unique); + return unique; + } + function Boolean(schema, references, value) { + const conversion = TryConvertBoolean(value); + return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references); + } + function Constructor(schema, references, value) { + if (check_1.ValueCheck.Check(schema, references, value)) + return create_1.ValueCreate.Create(schema, references); + const required = new Set(schema.returns.required || []); + const result = function () { }; + for (const [key, property] of globalThis.Object.entries(schema.returns.properties)) { + if (!required.has(key) && value.prototype[key] === undefined) + continue; + result.prototype[key] = Visit(property, references, value.prototype[key]); + } + return result; + } + function Enum(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Function(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Integer(schema, references, value) { + const conversion = TryConvertInteger(value); + return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references); + } + function Literal(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Never(schema, references, value) { + throw new ValueCastNeverTypeError(schema); + } + function Null(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Number(schema, references, value) { + const conversion = TryConvertNumber(value); + return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references); + } + function Object(schema, references, value) { + if (check_1.ValueCheck.Check(schema, references, value)) + return clone_1.ValueClone.Clone(value); + if (value === null || typeof value !== 'object') + return create_1.ValueCreate.Create(schema, references); + const required = new Set(schema.required || []); + const result = {}; + for (const [key, property] of globalThis.Object.entries(schema.properties)) { + if (!required.has(key) && value[key] === undefined) + continue; + result[key] = Visit(property, references, value[key]); + } + // additional schema properties + if (typeof schema.additionalProperties === 'object') { + const propertyKeys = globalThis.Object.keys(schema.properties); + for (const objectKey of globalThis.Object.keys(value)) { + if (propertyKeys.includes(objectKey)) + continue; + result[objectKey] = Visit(schema.additionalProperties, references, value[objectKey]); + } + } + return result; + } + function Promise(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Record(schema, references, value) { + if (check_1.ValueCheck.Check(schema, references, value)) + return clone_1.ValueClone.Clone(value); + if (value === null || typeof value !== 'object' || globalThis.Array.isArray(value)) + return create_1.ValueCreate.Create(schema, references); + const subschemaKey = globalThis.Object.keys(schema.patternProperties)[0]; + const subschema = schema.patternProperties[subschemaKey]; + const result = {}; + for (const [propKey, propValue] of globalThis.Object.entries(value)) { + result[propKey] = Visit(subschema, references, propValue); + } + return result; + } + function Recursive(schema, references, value) { + throw new ValueCastRecursiveTypeError(schema); + } + function Ref(schema, references, value) { + const reference = references.find((reference) => reference.$id === schema.$ref); + if (reference === undefined) + throw new ValueCastReferenceTypeError(schema); + return Visit(reference, references, value); + } + function Self(schema, references, value) { + const reference = references.find((reference) => reference.$id === schema.$ref); + if (reference === undefined) + throw new ValueCastReferenceTypeError(schema); + return Visit(reference, references, value); + } + function String(schema, references, value) { + const conversion = TryConvertString(value); + return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references); + } + function Tuple(schema, references, value) { + if (check_1.ValueCheck.Check(schema, references, value)) + return clone_1.ValueClone.Clone(value); + if (!globalThis.Array.isArray(value)) + return create_1.ValueCreate.Create(schema, references); + if (schema.items === undefined) + return []; + return schema.items.map((schema, index) => Visit(schema, references, value[index])); + } + function Undefined(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Union(schema, references, value) { + return UnionValueCast.Create(schema, references, value); + } + function Uint8Array(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Unknown(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Void(schema, references, value) { + return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); + } + function Visit(schema, references, value) { + const anyReferences = schema.$id === undefined ? references : [schema, ...references]; + const anySchema = schema; + switch (schema[Types.Kind]) { + case 'Any': + return Any(anySchema, anyReferences, value); + case 'Array': + return Array(anySchema, anyReferences, value); + case 'Boolean': + return Boolean(anySchema, anyReferences, value); + case 'Constructor': + return Constructor(anySchema, anyReferences, value); + case 'Enum': + return Enum(anySchema, anyReferences, value); + case 'Function': + return Function(anySchema, anyReferences, value); + case 'Integer': + return Integer(anySchema, anyReferences, value); + case 'Literal': + return Literal(anySchema, anyReferences, value); + case 'Never': + return Never(anySchema, anyReferences, value); + case 'Null': + return Null(anySchema, anyReferences, value); + case 'Number': + return Number(anySchema, anyReferences, value); + case 'Object': + return Object(anySchema, anyReferences, value); + case 'Promise': + return Promise(anySchema, anyReferences, value); + case 'Record': + return Record(anySchema, anyReferences, value); + case 'Rec': + return Recursive(anySchema, anyReferences, value); + case 'Ref': + return Ref(anySchema, anyReferences, value); + case 'Self': + return Self(anySchema, anyReferences, value); + case 'String': + return String(anySchema, anyReferences, value); + case 'Tuple': + return Tuple(anySchema, anyReferences, value); + case 'Undefined': + return Undefined(anySchema, anyReferences, value); + case 'Union': + return Union(anySchema, anyReferences, value); + case 'Uint8Array': + return Uint8Array(anySchema, anyReferences, value); + case 'Unknown': + return Unknown(anySchema, anyReferences, value); + case 'Void': + return Void(anySchema, anyReferences, value); + default: + throw new ValueCastUnknownTypeError(anySchema); + } + } + ValueCast.Visit = Visit; + function Cast(schema, references, value) { + return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value); + } + ValueCast.Cast = Cast; +})(ValueCast = exports.ValueCast || (exports.ValueCast = {})); diff --git a/node_modules/@sinclair/typebox/value/check.d.ts b/node_modules/@sinclair/typebox/value/check.d.ts new file mode 100644 index 0000000..b1f7742 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/check.d.ts @@ -0,0 +1,8 @@ +import * as Types from '../typebox'; +export declare class ValueCheckUnknownTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare namespace ValueCheck { + function Check(schema: T, references: [...R], value: any): boolean; +} diff --git a/node_modules/@sinclair/typebox/value/check.js b/node_modules/@sinclair/typebox/value/check.js new file mode 100644 index 0000000..346ca3c --- /dev/null +++ b/node_modules/@sinclair/typebox/value/check.js @@ -0,0 +1,331 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.ValueCheck = exports.ValueCheckUnknownTypeError = void 0; +const Types = require("../typebox"); +const format_1 = require("../format"); +class ValueCheckUnknownTypeError extends Error { + constructor(schema) { + super('ValueCheck: Unknown type'); + this.schema = schema; + } +} +exports.ValueCheckUnknownTypeError = ValueCheckUnknownTypeError; +var ValueCheck; +(function (ValueCheck) { + function Any(schema, references, value) { + return true; + } + function Array(schema, references, value) { + if (!globalThis.Array.isArray(value)) { + return false; + } + if (schema.minItems !== undefined && !(value.length >= schema.minItems)) { + return false; + } + if (schema.maxItems !== undefined && !(value.length <= schema.maxItems)) { + return false; + } + if (schema.uniqueItems === true && !(new Set(value).size === value.length)) { + return false; + } + return value.every((val) => Visit(schema.items, references, val)); + } + function Boolean(schema, references, value) { + return typeof value === 'boolean'; + } + function Constructor(schema, references, value) { + return Visit(schema.returns, references, value.prototype); + } + function Function(schema, references, value) { + return typeof value === 'function'; + } + function Integer(schema, references, value) { + if (!(typeof value === 'number')) { + return false; + } + if (!globalThis.Number.isInteger(value)) { + return false; + } + if (schema.multipleOf !== undefined && !(value % schema.multipleOf === 0)) { + return false; + } + if (schema.exclusiveMinimum !== undefined && !(value > schema.exclusiveMinimum)) { + return false; + } + if (schema.exclusiveMaximum !== undefined && !(value < schema.exclusiveMaximum)) { + return false; + } + if (schema.minimum !== undefined && !(value >= schema.minimum)) { + return false; + } + if (schema.maximum !== undefined && !(value <= schema.maximum)) { + return false; + } + return true; + } + function Literal(schema, references, value) { + return value === schema.const; + } + function Never(schema, references, value) { + return false; + } + function Null(schema, references, value) { + return value === null; + } + function Number(schema, references, value) { + if (!(typeof value === 'number')) { + return false; + } + if (schema.multipleOf && !(value % schema.multipleOf === 0)) { + return false; + } + if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) { + return false; + } + if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) { + return false; + } + if (schema.minimum && !(value >= schema.minimum)) { + return false; + } + if (schema.maximum && !(value <= schema.maximum)) { + return false; + } + return true; + } + function Object(schema, references, value) { + if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) { + return false; + } + if (schema.minProperties !== undefined && !(globalThis.Object.keys(value).length >= schema.minProperties)) { + return false; + } + if (schema.maxProperties !== undefined && !(globalThis.Object.keys(value).length <= schema.maxProperties)) { + return false; + } + const propertyKeys = globalThis.Object.keys(schema.properties); + if (schema.additionalProperties === false) { + // optimization: If the property key length matches the required keys length + // then we only need check that the values property key length matches that + // of the property key length. This is because exhaustive testing for values + // will occur in subsequent property tests. + if (schema.required && schema.required.length === propertyKeys.length && !(globalThis.Object.keys(value).length === propertyKeys.length)) { + return false; + } + else { + if (!globalThis.Object.keys(value).every((key) => propertyKeys.includes(key))) { + return false; + } + } + } + if (typeof schema.additionalProperties === 'object') { + for (const objectKey of globalThis.Object.keys(value)) { + if (propertyKeys.includes(objectKey)) + continue; + if (!Visit(schema.additionalProperties, references, value[objectKey])) { + return false; + } + } + } + for (const propertyKey of propertyKeys) { + const propertySchema = schema.properties[propertyKey]; + if (schema.required && schema.required.includes(propertyKey)) { + if (!Visit(propertySchema, references, value[propertyKey])) { + return false; + } + } + else { + if (value[propertyKey] !== undefined) { + if (!Visit(propertySchema, references, value[propertyKey])) { + return false; + } + } + } + } + return true; + } + function Promise(schema, references, value) { + return typeof value === 'object' && typeof value.then === 'function'; + } + function Record(schema, references, value) { + if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) { + return false; + } + const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; + const regex = new RegExp(keyPattern); + if (!globalThis.Object.keys(value).every((key) => regex.test(key))) { + return false; + } + for (const propValue of globalThis.Object.values(value)) { + if (!Visit(valueSchema, references, propValue)) + return false; + } + return true; + } + function Ref(schema, references, value) { + const reference = references.find((reference) => reference.$id === schema.$ref); + if (reference === undefined) + throw new Error(`ValueCheck.Ref: Cannot find schema with $id '${schema.$ref}'.`); + return Visit(reference, references, value); + } + function Self(schema, references, value) { + const reference = references.find((reference) => reference.$id === schema.$ref); + if (reference === undefined) + throw new Error(`ValueCheck.Self: Cannot find schema with $id '${schema.$ref}'.`); + return Visit(reference, references, value); + } + function String(schema, references, value) { + if (!(typeof value === 'string')) { + return false; + } + if (schema.minLength !== undefined) { + if (!(value.length >= schema.minLength)) + return false; + } + if (schema.maxLength !== undefined) { + if (!(value.length <= schema.maxLength)) + return false; + } + if (schema.pattern !== undefined) { + const regex = new RegExp(schema.pattern); + if (!regex.test(value)) + return false; + } + if (schema.format !== undefined) { + if (!format_1.Format.Has(schema.format)) + return false; + const func = format_1.Format.Get(schema.format); + return func(value); + } + return true; + } + function Tuple(schema, references, value) { + if (!globalThis.Array.isArray(value)) { + return false; + } + if (schema.items === undefined && !(value.length === 0)) { + return false; + } + if (!(value.length === schema.maxItems)) { + return false; + } + if (!schema.items) { + return true; + } + for (let i = 0; i < schema.items.length; i++) { + if (!Visit(schema.items[i], references, value[i])) + return false; + } + return true; + } + function Undefined(schema, references, value) { + return value === undefined; + } + function Union(schema, references, value) { + return schema.anyOf.some((inner) => Visit(inner, references, value)); + } + function Uint8Array(schema, references, value) { + if (!(value instanceof globalThis.Uint8Array)) { + return false; + } + if (schema.maxByteLength && !(value.length <= schema.maxByteLength)) { + return false; + } + if (schema.minByteLength && !(value.length >= schema.minByteLength)) { + return false; + } + return true; + } + function Unknown(schema, references, value) { + return true; + } + function Void(schema, references, value) { + return value === null; + } + function Visit(schema, references, value) { + const anyReferences = schema.$id === undefined ? references : [schema, ...references]; + const anySchema = schema; + switch (anySchema[Types.Kind]) { + case 'Any': + return Any(anySchema, anyReferences, value); + case 'Array': + return Array(anySchema, anyReferences, value); + case 'Boolean': + return Boolean(anySchema, anyReferences, value); + case 'Constructor': + return Constructor(anySchema, anyReferences, value); + case 'Function': + return Function(anySchema, anyReferences, value); + case 'Integer': + return Integer(anySchema, anyReferences, value); + case 'Literal': + return Literal(anySchema, anyReferences, value); + case 'Never': + return Never(anySchema, anyReferences, value); + case 'Null': + return Null(anySchema, anyReferences, value); + case 'Number': + return Number(anySchema, anyReferences, value); + case 'Object': + return Object(anySchema, anyReferences, value); + case 'Promise': + return Promise(anySchema, anyReferences, value); + case 'Record': + return Record(anySchema, anyReferences, value); + case 'Ref': + return Ref(anySchema, anyReferences, value); + case 'Self': + return Self(anySchema, anyReferences, value); + case 'String': + return String(anySchema, anyReferences, value); + case 'Tuple': + return Tuple(anySchema, anyReferences, value); + case 'Undefined': + return Undefined(anySchema, anyReferences, value); + case 'Union': + return Union(anySchema, anyReferences, value); + case 'Uint8Array': + return Uint8Array(anySchema, anyReferences, value); + case 'Unknown': + return Unknown(anySchema, anyReferences, value); + case 'Void': + return Void(anySchema, anyReferences, value); + default: + throw new ValueCheckUnknownTypeError(anySchema); + } + } + // ------------------------------------------------------------------------- + // Check + // ------------------------------------------------------------------------- + function Check(schema, references, value) { + return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value); + } + ValueCheck.Check = Check; +})(ValueCheck = exports.ValueCheck || (exports.ValueCheck = {})); diff --git a/node_modules/@sinclair/typebox/value/clone.d.ts b/node_modules/@sinclair/typebox/value/clone.d.ts new file mode 100644 index 0000000..5ca0adf --- /dev/null +++ b/node_modules/@sinclair/typebox/value/clone.d.ts @@ -0,0 +1,3 @@ +export declare namespace ValueClone { + function Clone(value: T): T; +} diff --git a/node_modules/@sinclair/typebox/value/clone.js b/node_modules/@sinclair/typebox/value/clone.js new file mode 100644 index 0000000..503b3fd --- /dev/null +++ b/node_modules/@sinclair/typebox/value/clone.js @@ -0,0 +1,65 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.ValueClone = void 0; +const is_1 = require("./is"); +var ValueClone; +(function (ValueClone) { + function Object(value) { + const keys = [...globalThis.Object.keys(value), ...globalThis.Object.getOwnPropertySymbols(value)]; + return keys.reduce((acc, key) => ({ ...acc, [key]: Clone(value[key]) }), {}); + } + function Array(value) { + return value.map((element) => Clone(element)); + } + function TypedArray(value) { + return value.slice(); + } + function Value(value) { + return value; + } + function Clone(value) { + if (is_1.Is.Object(value)) { + return Object(value); + } + else if (is_1.Is.Array(value)) { + return Array(value); + } + else if (is_1.Is.TypedArray(value)) { + return TypedArray(value); + } + else if (is_1.Is.Value(value)) { + return Value(value); + } + else { + throw new Error('ValueClone: Unable to clone value'); + } + } + ValueClone.Clone = Clone; +})(ValueClone = exports.ValueClone || (exports.ValueClone = {})); diff --git a/node_modules/@sinclair/typebox/value/create.d.ts b/node_modules/@sinclair/typebox/value/create.d.ts new file mode 100644 index 0000000..9ac7878 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/create.d.ts @@ -0,0 +1,14 @@ +import * as Types from '../typebox'; +export declare class ValueCreateUnknownTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare class ValueCreateNeverTypeError extends Error { + readonly schema: Types.TSchema; + constructor(schema: Types.TSchema); +} +export declare namespace ValueCreate { + /** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */ + function Visit(schema: T, references: Types.TSchema[]): Types.Static; + function Create(schema: T, references: [...R]): Types.Static; +} diff --git a/node_modules/@sinclair/typebox/value/create.js b/node_modules/@sinclair/typebox/value/create.js new file mode 100644 index 0000000..58a5f25 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/create.js @@ -0,0 +1,357 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.ValueCreate = exports.ValueCreateNeverTypeError = exports.ValueCreateUnknownTypeError = void 0; +const Types = require("../typebox"); +class ValueCreateUnknownTypeError extends Error { + constructor(schema) { + super('ValueCreate: Unknown type'); + this.schema = schema; + } +} +exports.ValueCreateUnknownTypeError = ValueCreateUnknownTypeError; +class ValueCreateNeverTypeError extends Error { + constructor(schema) { + super('ValueCreate: Never types cannot be created'); + this.schema = schema; + } +} +exports.ValueCreateNeverTypeError = ValueCreateNeverTypeError; +var ValueCreate; +(function (ValueCreate) { + function Any(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else { + return {}; + } + } + function Array(schema, references) { + if (schema.uniqueItems === true && schema.default === undefined) { + throw new Error('ValueCreate.Array: Arrays with uniqueItems require a default value'); + } + else if (schema.default !== undefined) { + return schema.default; + } + else if (schema.minItems !== undefined) { + return globalThis.Array.from({ length: schema.minItems }).map((item) => { + return ValueCreate.Create(schema.items, references); + }); + } + else { + return []; + } + } + function Boolean(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else { + return false; + } + } + function Constructor(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else { + const value = ValueCreate.Create(schema.returns, references); + if (typeof value === 'object' && !globalThis.Array.isArray(value)) { + return class { + constructor() { + for (const [key, val] of globalThis.Object.entries(value)) { + const self = this; + self[key] = val; + } + } + }; + } + else { + return class { + }; + } + } + } + function Enum(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else if (schema.anyOf.length === 0) { + throw new Error('ValueCreate.Enum: Cannot create default enum value as this enum has no items'); + } + else { + return schema.anyOf[0].const; + } + } + function Function(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else { + return () => ValueCreate.Create(schema.returns, references); + } + } + function Integer(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else if (schema.minimum !== undefined) { + return schema.minimum; + } + else { + return 0; + } + } + function Literal(schema, references) { + return schema.const; + } + function Never(schema, references) { + throw new ValueCreateNeverTypeError(schema); + } + function Null(schema, references) { + return null; + } + function Number(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else if (schema.minimum !== undefined) { + return schema.minimum; + } + else { + return 0; + } + } + function Object(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else { + const required = new Set(schema.required); + return (schema.default || + globalThis.Object.entries(schema.properties).reduce((acc, [key, schema]) => { + return required.has(key) ? { ...acc, [key]: ValueCreate.Create(schema, references) } : { ...acc }; + }, {})); + } + } + function Promise(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else { + return globalThis.Promise.resolve(ValueCreate.Create(schema.item, references)); + } + } + function Record(schema, references) { + const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; + if (schema.default !== undefined) { + return schema.default; + } + else if (!(keyPattern === '^.*$' || keyPattern === '^(0|[1-9][0-9]*)$')) { + const propertyKeys = keyPattern.slice(1, keyPattern.length - 1).split('|'); + return propertyKeys.reduce((acc, key) => { + return { ...acc, [key]: Create(valueSchema, references) }; + }, {}); + } + else { + return {}; + } + } + function Recursive(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else { + throw new Error('ValueCreate.Recursive: Recursive types require a default value'); + } + } + function Ref(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else { + const reference = references.find((reference) => reference.$id === schema.$ref); + if (reference === undefined) + throw new Error(`ValueCreate.Ref: Cannot find schema with $id '${schema.$ref}'.`); + return Visit(reference, references); + } + } + function Self(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else { + const reference = references.find((reference) => reference.$id === schema.$ref); + if (reference === undefined) + throw new Error(`ValueCreate.Self: Cannot locate schema with $id '${schema.$ref}'`); + return Visit(reference, references); + } + } + function String(schema, references) { + if (schema.pattern !== undefined) { + if (schema.default === undefined) { + throw new Error('ValueCreate.String: String types with patterns must specify a default value'); + } + else { + return schema.default; + } + } + else if (schema.format !== undefined) { + if (schema.default === undefined) { + throw new Error('ValueCreate.String: String types with formats must specify a default value'); + } + else { + return schema.default; + } + } + else { + if (schema.default !== undefined) { + return schema.default; + } + else if (schema.minLength !== undefined) { + return globalThis.Array.from({ length: schema.minLength }) + .map(() => '.') + .join(''); + } + else { + return ''; + } + } + } + function Tuple(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + if (schema.items === undefined) { + return []; + } + else { + return globalThis.Array.from({ length: schema.minItems }).map((_, index) => ValueCreate.Create(schema.items[index], references)); + } + } + function Undefined(schema, references) { + return undefined; + } + function Union(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else if (schema.anyOf.length === 0) { + throw new Error('ValueCreate.Union: Cannot create Union with zero variants'); + } + else { + return ValueCreate.Create(schema.anyOf[0], references); + } + } + function Uint8Array(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else if (schema.minByteLength !== undefined) { + return new globalThis.Uint8Array(schema.minByteLength); + } + else { + return new globalThis.Uint8Array(0); + } + } + function Unknown(schema, references) { + if (schema.default !== undefined) { + return schema.default; + } + else { + return {}; + } + } + function Void(schema, references) { + return null; + } + /** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */ + function Visit(schema, references) { + const anyReferences = schema.$id === undefined ? references : [schema, ...references]; + const anySchema = schema; + switch (anySchema[Types.Kind]) { + case 'Any': + return Any(anySchema, anyReferences); + case 'Array': + return Array(anySchema, anyReferences); + case 'Boolean': + return Boolean(anySchema, anyReferences); + case 'Constructor': + return Constructor(anySchema, anyReferences); + case 'Enum': + return Enum(anySchema, anyReferences); + case 'Function': + return Function(anySchema, anyReferences); + case 'Integer': + return Integer(anySchema, anyReferences); + case 'Literal': + return Literal(anySchema, anyReferences); + case 'Never': + return Never(anySchema, anyReferences); + case 'Null': + return Null(anySchema, anyReferences); + case 'Number': + return Number(anySchema, anyReferences); + case 'Object': + return Object(anySchema, anyReferences); + case 'Promise': + return Promise(anySchema, anyReferences); + case 'Record': + return Record(anySchema, anyReferences); + case 'Rec': + return Recursive(anySchema, anyReferences); + case 'Ref': + return Ref(anySchema, anyReferences); + case 'Self': + return Self(anySchema, anyReferences); + case 'String': + return String(anySchema, anyReferences); + case 'Tuple': + return Tuple(anySchema, anyReferences); + case 'Undefined': + return Undefined(anySchema, anyReferences); + case 'Union': + return Union(anySchema, anyReferences); + case 'Uint8Array': + return Uint8Array(anySchema, anyReferences); + case 'Unknown': + return Unknown(anySchema, anyReferences); + case 'Void': + return Void(anySchema, anyReferences); + default: + throw new ValueCreateUnknownTypeError(anySchema); + } + } + ValueCreate.Visit = Visit; + function Create(schema, references) { + return Visit(schema, references); + } + ValueCreate.Create = Create; +})(ValueCreate = exports.ValueCreate || (exports.ValueCreate = {})); diff --git a/node_modules/@sinclair/typebox/value/delta.d.ts b/node_modules/@sinclair/typebox/value/delta.d.ts new file mode 100644 index 0000000..cb60b01 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/delta.d.ts @@ -0,0 +1,22 @@ +export declare type Edit = Insert | Update | Delete; +export interface Insert { + brand: T; + type: 'insert'; + path: string; + value: any; +} +export interface Update { + brand: T; + type: 'update'; + path: string; + value: any; +} +export interface Delete { + brand: T; + type: 'delete'; + path: string; +} +export declare namespace ValueDelta { + function Diff(current: T, next: T): Edit[]; + function Patch(current: T, edits: Edit[]): T; +} diff --git a/node_modules/@sinclair/typebox/value/delta.js b/node_modules/@sinclair/typebox/value/delta.js new file mode 100644 index 0000000..c1a68ed --- /dev/null +++ b/node_modules/@sinclair/typebox/value/delta.js @@ -0,0 +1,168 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.ValueDelta = void 0; +const is_1 = require("./is"); +const clone_1 = require("./clone"); +const pointer_1 = require("./pointer"); +var ValueDelta; +(function (ValueDelta) { + // --------------------------------------------------------------------- + // Edits + // --------------------------------------------------------------------- + function Update(path, value) { + return { type: 'update', path, value }; + } + function Insert(path, value) { + return { type: 'insert', path, value }; + } + function Delete(path) { + return { type: 'delete', path }; + } + // --------------------------------------------------------------------- + // Diff + // --------------------------------------------------------------------- + function* Object(path, current, next) { + if (!is_1.Is.Object(next)) + return yield Update(path, next); + const currentKeys = [...globalThis.Object.keys(current), ...globalThis.Object.getOwnPropertySymbols(current)]; + const nextKeys = [...globalThis.Object.keys(next), ...globalThis.Object.getOwnPropertySymbols(next)]; + for (const key of currentKeys) { + if (typeof key === 'symbol') + throw Error('ValueDelta: Cannot produce diff symbol keys'); + if (next[key] === undefined && nextKeys.includes(key)) + yield Update(`${path}/${String(key)}`, undefined); + } + for (const key of nextKeys) { + if (current[key] === undefined || next[key] === undefined) + continue; + if (typeof key === 'symbol') + throw Error('ValueDelta: Cannot produce diff symbol keys'); + yield* Visit(`${path}/${String(key)}`, current[key], next[key]); + } + for (const key of nextKeys) { + if (typeof key === 'symbol') + throw Error('ValueDelta: Cannot produce diff symbol keys'); + if (current[key] === undefined) + yield Insert(`${path}/${String(key)}`, next[key]); + } + for (const key of currentKeys.reverse()) { + if (typeof key === 'symbol') + throw Error('ValueDelta: Cannot produce diff symbol keys'); + if (next[key] === undefined && !nextKeys.includes(key)) + yield Delete(`${path}/${String(key)}`); + } + } + function* Array(path, current, next) { + if (!is_1.Is.Array(next)) + return yield Update(path, next); + for (let i = 0; i < Math.min(current.length, next.length); i++) { + yield* Visit(`${path}/${i}`, current[i], next[i]); + } + for (let i = 0; i < next.length; i++) { + if (i < current.length) + continue; + yield Insert(`${path}/${i}`, next[i]); + } + for (let i = current.length - 1; i >= 0; i--) { + if (i < next.length) + continue; + yield Delete(`${path}/${i}`); + } + } + function* TypedArray(path, current, next) { + if (!is_1.Is.TypedArray(next) || current.length !== next.length || globalThis.Object.getPrototypeOf(current).constructor.name !== globalThis.Object.getPrototypeOf(next).constructor.name) + return yield Update(path, next); + for (let i = 0; i < Math.min(current.length, next.length); i++) { + yield* Visit(`${path}/${i}`, current[i], next[i]); + } + } + function* Value(path, current, next) { + if (current === next) + return; + yield Update(path, next); + } + function* Visit(path, current, next) { + if (is_1.Is.Object(current)) { + return yield* Object(path, current, next); + } + else if (is_1.Is.Array(current)) { + return yield* Array(path, current, next); + } + else if (is_1.Is.TypedArray(current)) { + return yield* TypedArray(path, current, next); + } + else if (is_1.Is.Value(current)) { + return yield* Value(path, current, next); + } + else { + throw new Error('ValueDelta: Cannot produce edits for value'); + } + } + function Diff(current, next) { + return [...Visit('', current, next)]; + } + ValueDelta.Diff = Diff; + // --------------------------------------------------------------------- + // Patch + // --------------------------------------------------------------------- + function IsRootUpdate(edits) { + return edits.length > 0 && edits[0].path === '' && edits[0].type === 'update'; + } + function IsIdentity(edits) { + return edits.length === 0; + } + function Patch(current, edits) { + if (IsRootUpdate(edits)) { + return clone_1.ValueClone.Clone(edits[0].value); + } + if (IsIdentity(edits)) { + return clone_1.ValueClone.Clone(current); + } + const clone = clone_1.ValueClone.Clone(current); + for (const edit of edits) { + switch (edit.type) { + case 'insert': { + pointer_1.ValuePointer.Set(clone, edit.path, edit.value); + break; + } + case 'update': { + pointer_1.ValuePointer.Set(clone, edit.path, edit.value); + break; + } + case 'delete': { + pointer_1.ValuePointer.Delete(clone, edit.path); + break; + } + } + } + return clone; + } + ValueDelta.Patch = Patch; +})(ValueDelta = exports.ValueDelta || (exports.ValueDelta = {})); diff --git a/node_modules/@sinclair/typebox/value/equal.d.ts b/node_modules/@sinclair/typebox/value/equal.d.ts new file mode 100644 index 0000000..785c2b8 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/equal.d.ts @@ -0,0 +1,3 @@ +export declare namespace ValueEqual { + function Equal(left: T, right: unknown): right is T; +} diff --git a/node_modules/@sinclair/typebox/value/equal.js b/node_modules/@sinclair/typebox/value/equal.js new file mode 100644 index 0000000..a0dc116 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/equal.js @@ -0,0 +1,74 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.ValueEqual = void 0; +const is_1 = require("./is"); +var ValueEqual; +(function (ValueEqual) { + function Object(left, right) { + if (!is_1.Is.Object(right)) + return false; + const leftKeys = [...globalThis.Object.keys(left), ...globalThis.Object.getOwnPropertySymbols(left)]; + const rightKeys = [...globalThis.Object.keys(right), ...globalThis.Object.getOwnPropertySymbols(right)]; + if (leftKeys.length !== rightKeys.length) + return false; + return leftKeys.every((key) => Equal(left[key], right[key])); + } + function Array(left, right) { + if (!is_1.Is.Array(right) || left.length !== right.length) + return false; + return left.every((value, index) => Equal(value, right[index])); + } + function TypedArray(left, right) { + if (!is_1.Is.TypedArray(right) || left.length !== right.length || globalThis.Object.getPrototypeOf(left).constructor.name !== globalThis.Object.getPrototypeOf(right).constructor.name) + return false; + return left.every((value, index) => Equal(value, right[index])); + } + function Value(left, right) { + return left === right; + } + function Equal(left, right) { + if (is_1.Is.Object(left)) { + return Object(left, right); + } + else if (is_1.Is.TypedArray(left)) { + return TypedArray(left, right); + } + else if (is_1.Is.Array(left)) { + return Array(left, right); + } + else if (is_1.Is.Value(left)) { + return Value(left, right); + } + else { + throw new Error('ValueEquals: Unable to compare value'); + } + } + ValueEqual.Equal = Equal; +})(ValueEqual = exports.ValueEqual || (exports.ValueEqual = {})); diff --git a/node_modules/@sinclair/typebox/value/index.d.ts b/node_modules/@sinclair/typebox/value/index.d.ts new file mode 100644 index 0000000..4cfd5e3 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/index.d.ts @@ -0,0 +1,3 @@ +export { ValueError, ValueErrorType } from '../errors/index'; +export * from './pointer'; +export * from './value'; diff --git a/node_modules/@sinclair/typebox/value/index.js b/node_modules/@sinclair/typebox/value/index.js new file mode 100644 index 0000000..801ed4f --- /dev/null +++ b/node_modules/@sinclair/typebox/value/index.js @@ -0,0 +1,48 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ValueErrorType = void 0; +var index_1 = require("../errors/index"); +Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } }); +__exportStar(require("./pointer"), exports); +__exportStar(require("./value"), exports); diff --git a/node_modules/@sinclair/typebox/value/is.d.ts b/node_modules/@sinclair/typebox/value/is.d.ts new file mode 100644 index 0000000..57da794 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/is.d.ts @@ -0,0 +1,10 @@ +export declare type ValueType = null | undefined | Function | symbol | bigint | number | boolean | string; +export declare type ObjectType = Record; +export declare type TypedArrayType = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; +export declare type ArrayType = unknown[]; +export declare namespace Is { + function Object(value: unknown): value is ObjectType; + function Array(value: unknown): value is ArrayType; + function Value(value: unknown): value is ValueType; + function TypedArray(value: unknown): value is TypedArrayType; +} diff --git a/node_modules/@sinclair/typebox/value/is.js b/node_modules/@sinclair/typebox/value/is.js new file mode 100644 index 0000000..a96b05d --- /dev/null +++ b/node_modules/@sinclair/typebox/value/is.js @@ -0,0 +1,49 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.Is = void 0; +var Is; +(function (Is) { + function Object(value) { + return value !== null && typeof value === 'object' && !globalThis.Array.isArray(value) && !ArrayBuffer.isView(value); + } + Is.Object = Object; + function Array(value) { + return globalThis.Array.isArray(value) && !ArrayBuffer.isView(value); + } + Is.Array = Array; + function Value(value) { + return value === null || value === undefined || typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string'; + } + Is.Value = Value; + function TypedArray(value) { + return ArrayBuffer.isView(value); + } + Is.TypedArray = TypedArray; +})(Is = exports.Is || (exports.Is = {})); diff --git a/node_modules/@sinclair/typebox/value/pointer.d.ts b/node_modules/@sinclair/typebox/value/pointer.d.ts new file mode 100644 index 0000000..d548b3d --- /dev/null +++ b/node_modules/@sinclair/typebox/value/pointer.d.ts @@ -0,0 +1,24 @@ +export declare class ValuePointerRootSetError extends Error { + readonly value: unknown; + readonly path: string; + readonly update: unknown; + constructor(value: unknown, path: string, update: unknown); +} +export declare class ValuePointerRootDeleteError extends Error { + readonly value: unknown; + readonly path: string; + constructor(value: unknown, path: string); +} +/** ValuePointer performs mutable operations on values using RFC6901 Json Pointers */ +export declare namespace ValuePointer { + /** Formats the given pointer into navigable key components */ + function Format(pointer: string): IterableIterator; + /** Sets the value at the given pointer. If the value at the pointer does not exist it is created */ + function Set(value: any, pointer: string, update: unknown): void; + /** Deletes a value at the given pointer */ + function Delete(value: any, pointer: string): void; + /** Returns true if a value exists at the given pointer */ + function Has(value: any, pointer: string): boolean; + /** Gets the value at the given pointer */ + function Get(value: any, pointer: string): any; +} diff --git a/node_modules/@sinclair/typebox/value/pointer.js b/node_modules/@sinclair/typebox/value/pointer.js new file mode 100644 index 0000000..e69e1a5 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/pointer.js @@ -0,0 +1,142 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.ValuePointer = exports.ValuePointerRootDeleteError = exports.ValuePointerRootSetError = void 0; +class ValuePointerRootSetError extends Error { + constructor(value, path, update) { + super('ValuePointer: Cannot set root value'); + this.value = value; + this.path = path; + this.update = update; + } +} +exports.ValuePointerRootSetError = ValuePointerRootSetError; +class ValuePointerRootDeleteError extends Error { + constructor(value, path) { + super('ValuePointer: Cannot delete root value'); + this.value = value; + this.path = path; + } +} +exports.ValuePointerRootDeleteError = ValuePointerRootDeleteError; +/** ValuePointer performs mutable operations on values using RFC6901 Json Pointers */ +var ValuePointer; +(function (ValuePointer) { + function Escape(component) { + return component.indexOf('~') === -1 ? component : component.replace(/~1/g, '/').replace(/~0/g, '~'); + } + /** Formats the given pointer into navigable key components */ + function* Format(pointer) { + if (pointer === '') + return; + let [start, end] = [0, 0]; + for (let i = 0; i < pointer.length; i++) { + const char = pointer.charAt(i); + if (char === '/') { + if (i === 0) { + start = i + 1; + } + else { + end = i; + yield Escape(pointer.slice(start, end)); + start = i + 1; + } + } + else { + end = i; + } + } + yield Escape(pointer.slice(start)); + } + ValuePointer.Format = Format; + /** Sets the value at the given pointer. If the value at the pointer does not exist it is created */ + function Set(value, pointer, update) { + if (pointer === '') + throw new ValuePointerRootSetError(value, pointer, update); + let [owner, next, key] = [null, value, '']; + for (const component of Format(pointer)) { + if (next[component] === undefined) + next[component] = {}; + owner = next; + next = next[component]; + key = component; + } + owner[key] = update; + } + ValuePointer.Set = Set; + /** Deletes a value at the given pointer */ + function Delete(value, pointer) { + if (pointer === '') + throw new ValuePointerRootDeleteError(value, pointer); + let [owner, next, key] = [null, value, '']; + for (const component of Format(pointer)) { + if (next[component] === undefined || next[component] === null) + return; + owner = next; + next = next[component]; + key = component; + } + if (globalThis.Array.isArray(owner)) { + const index = parseInt(key); + owner.splice(index, 1); + } + else { + delete owner[key]; + } + } + ValuePointer.Delete = Delete; + /** Returns true if a value exists at the given pointer */ + function Has(value, pointer) { + if (pointer === '') + return true; + let [owner, next, key] = [null, value, '']; + for (const component of Format(pointer)) { + if (next[component] === undefined) + return false; + owner = next; + next = next[component]; + key = component; + } + return globalThis.Object.getOwnPropertyNames(owner).includes(key); + } + ValuePointer.Has = Has; + /** Gets the value at the given pointer */ + function Get(value, pointer) { + if (pointer === '') + return value; + let current = value; + for (const component of Format(pointer)) { + if (current[component] === undefined) + return undefined; + current = current[component]; + } + return current; + } + ValuePointer.Get = Get; +})(ValuePointer = exports.ValuePointer || (exports.ValuePointer = {})); diff --git a/node_modules/@sinclair/typebox/value/value.d.ts b/node_modules/@sinclair/typebox/value/value.d.ts new file mode 100644 index 0000000..3525cae --- /dev/null +++ b/node_modules/@sinclair/typebox/value/value.d.ts @@ -0,0 +1,31 @@ +import * as Types from '../typebox'; +import { ValueError } from '../errors/index'; +import { Edit } from './delta'; +export type { Edit } from './delta'; +/** Value performs immutable operations on values */ +export declare namespace Value { + /** Casts a value into a given type. The return value will retain as much information of the original value as possible. Cast will convert string, number and boolean values if a reasonable conversion is possible. */ + function Cast(schema: T, references: [...R], value: unknown): Types.Static; + /** Casts a value into a given type. The return value will retain as much information of the original value as possible. Cast will convert string, number and boolean values if a reasonable conversion is possible. */ + function Cast(schema: T, value: unknown): Types.Static; + /** Creates a value from the given type */ + function Create(schema: T, references: [...R]): Types.Static; + /** Creates a value from the given type */ + function Create(schema: T): Types.Static; + /** Returns true if the value matches the given type. */ + function Check(schema: T, references: [...R], value: unknown): value is Types.Static; + /** Returns true if the value matches the given type. */ + function Check(schema: T, value: unknown): value is Types.Static; + /** Returns an iterator for each error in this value. */ + function Errors(schema: T, references: [...R], value: unknown): IterableIterator; + /** Returns an iterator for each error in this value. */ + function Errors(schema: T, value: unknown): IterableIterator; + /** Returns true if left and right values are structurally equal */ + function Equal(left: T, right: unknown): right is T; + /** Returns a structural clone of the given value */ + function Clone(value: T): T; + /** Returns edits to transform the current value into the next value */ + function Diff(current: T, next: T): Edit[]; + /** Returns a new value with edits applied to the given value */ + function Patch(current: T, edits: Edit[]): T; +} diff --git a/node_modules/@sinclair/typebox/value/value.js b/node_modules/@sinclair/typebox/value/value.js new file mode 100644 index 0000000..b7dbff3 --- /dev/null +++ b/node_modules/@sinclair/typebox/value/value.js @@ -0,0 +1,81 @@ +"use strict"; +/*-------------------------------------------------------------------------- + +@sinclair/typebox/value + +The MIT License (MIT) + +Copyright (c) 2022 Haydn Paterson (sinclair) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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.defineProperty(exports, "__esModule", { value: true }); +exports.Value = void 0; +const index_1 = require("../errors/index"); +const equal_1 = require("./equal"); +const cast_1 = require("./cast"); +const clone_1 = require("./clone"); +const create_1 = require("./create"); +const check_1 = require("./check"); +const delta_1 = require("./delta"); +/** Value performs immutable operations on values */ +var Value; +(function (Value) { + function Cast(...args) { + const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]]; + return cast_1.ValueCast.Cast(schema, references, value); + } + Value.Cast = Cast; + function Create(...args) { + const [schema, references] = args.length === 2 ? [args[0], args[1]] : [args[0], []]; + return create_1.ValueCreate.Create(schema, references); + } + Value.Create = Create; + function Check(...args) { + const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]]; + return check_1.ValueCheck.Check(schema, references, value); + } + Value.Check = Check; + function* Errors(...args) { + const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]]; + yield* index_1.ValueErrors.Errors(schema, references, value); + } + Value.Errors = Errors; + /** Returns true if left and right values are structurally equal */ + function Equal(left, right) { + return equal_1.ValueEqual.Equal(left, right); + } + Value.Equal = Equal; + /** Returns a structural clone of the given value */ + function Clone(value) { + return clone_1.ValueClone.Clone(value); + } + Value.Clone = Clone; + /** Returns edits to transform the current value into the next value */ + function Diff(current, next) { + return delta_1.ValueDelta.Diff(current, next); + } + Value.Diff = Diff; + /** Returns a new value with edits applied to the given value */ + function Patch(current, edits) { + return delta_1.ValueDelta.Patch(current, edits); + } + Value.Patch = Patch; +})(Value = exports.Value || (exports.Value = {})); diff --git a/node_modules/@sinonjs/commons/CHANGES.md b/node_modules/@sinonjs/commons/CHANGES.md new file mode 100644 index 0000000..9d30695 --- /dev/null +++ b/node_modules/@sinonjs/commons/CHANGES.md @@ -0,0 +1,57 @@ +# Changes + +## 1.8.3 + +- [`6af2d0c`](https://github.com/sinonjs/commons/commit/6af2d0cf33e9fd1e4aaef5308fd16a9cd78a5782) + Bump y18n from 4.0.0 to 4.0.1 (dependabot[bot]) + > + > Bumps [y18n](https://github.com/yargs/y18n) from 4.0.0 to 4.0.1. + > - [Release notes](https://github.com/yargs/y18n/releases) + > - [Changelog](https://github.com/yargs/y18n/blob/master/CHANGELOG.md) + > - [Commits](https://github.com/yargs/y18n/commits) + > + > Signed-off-by: dependabot[bot] + +_Released on 2021-04-08._ + +## 1.8.2 + +- [`6b7a796`](https://github.com/sinonjs/commons/commit/6b7a796ffc088b43dc283cc4477a7d641720dc96) + Add .d.ts files to package (Morgan Roderick) + > + > In order to improve the experience of TypeScript users, we are compiling + > `.d.ts` files from the JSDoc and distributing them with the package + > + +_Released on 2021-01-13._ + +## 1.8.1 + +- [`07b9e7a`](https://github.com/sinonjs/commons/commit/07b9e7a1d784771273a9a58d74945bbc7319b5d4) + Optimize npm package size (Uladzimir Havenchyk) + +_Released on 2020-07-17._ + +## 1.8.0 + +- [`4282205`](https://github.com/sinonjs/commons/commit/4282205343a4dcde2a35ccf2a8c2094300dad369) + Emit deprecationg warnings in node, and keep console info in browsers (mshaaban0) + +_Released on 2020-05-20._ + +## 1.7.2 + +- [`76ad9c1`](https://github.com/sinonjs/commons/commit/76ad9c16bad29f72420ed55bdf45b65d076108c8) + Fix generators causing exceptions in function-name (Sebastian Mayr) + +_Released on 2020-04-08._ + +## 1.7.1 + +- [`0486d25`](https://github.com/sinonjs/commons/commit/0486d250ecec9b5f9aa2210357767e413f4162d3) + Upgrade eslint-config-sinon, add eslint-plugin-jsdoc (Morgan Roderick) + > + > This adds linting of jsdoc + > + +_Released on 2020-02-19._ diff --git a/node_modules/@sinonjs/commons/LICENSE b/node_modules/@sinonjs/commons/LICENSE new file mode 100644 index 0000000..5a77f0a --- /dev/null +++ b/node_modules/@sinonjs/commons/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2018, Sinon.JS +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 the copyright holder 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 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. diff --git a/node_modules/@sinonjs/commons/README.md b/node_modules/@sinonjs/commons/README.md new file mode 100644 index 0000000..9c420ba --- /dev/null +++ b/node_modules/@sinonjs/commons/README.md @@ -0,0 +1,16 @@ +# commons + +[![CircleCI](https://circleci.com/gh/sinonjs/commons.svg?style=svg)](https://circleci.com/gh/sinonjs/commons) +[![codecov](https://codecov.io/gh/sinonjs/commons/branch/master/graph/badge.svg)](https://codecov.io/gh/sinonjs/commons) +Contributor Covenant + +Simple functions shared among the sinon end user libraries + +## Rules + +- Follows the [Sinon.JS compatibility](https://github.com/sinonjs/sinon/blob/master/CONTRIBUTING.md#compatibility) +- 100% test coverage +- Code formatted using [Prettier](https://prettier.io) +- No side effects welcome! (only pure functions) +- No platform specific functions +- One export per file (any bundler can do tree shaking) diff --git a/node_modules/@sinonjs/commons/lib/called-in-order.js b/node_modules/@sinonjs/commons/lib/called-in-order.js new file mode 100644 index 0000000..4edb67f --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/called-in-order.js @@ -0,0 +1,57 @@ +"use strict"; + +var every = require("./prototypes/array").every; + +/** + * @private + */ +function hasCallsLeft(callMap, spy) { + if (callMap[spy.id] === undefined) { + callMap[spy.id] = 0; + } + + return callMap[spy.id] < spy.callCount; +} + +/** + * @private + */ +function checkAdjacentCalls(callMap, spy, index, spies) { + var calledBeforeNext = true; + + if (index !== spies.length - 1) { + calledBeforeNext = spy.calledBefore(spies[index + 1]); + } + + if (hasCallsLeft(callMap, spy) && calledBeforeNext) { + callMap[spy.id] += 1; + return true; + } + + return false; +} + +/** + * A Sinon proxy object (fake, spy, stub) + * + * @typedef {object} SinonProxy + * @property {Function} calledBefore - A method that determines if this proxy was called before another one + * @property {string} id - Some id + * @property {number} callCount - Number of times this proxy has been called + */ + +/** + * Returns true when the spies have been called in the order they were supplied in + * + * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments + * @returns {boolean} true when spies are called in order, false otherwise + */ +function calledInOrder(spies) { + var callMap = {}; + // eslint-disable-next-line no-underscore-dangle + var _spies = arguments.length > 1 ? arguments : spies; + + return every(_spies, checkAdjacentCalls.bind(null, callMap)); +} + +module.exports = calledInOrder; diff --git a/node_modules/@sinonjs/commons/lib/called-in-order.test.js b/node_modules/@sinonjs/commons/lib/called-in-order.test.js new file mode 100644 index 0000000..00d8b8b --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/called-in-order.test.js @@ -0,0 +1,121 @@ +"use strict"; + +var assert = require("@sinonjs/referee-sinon").assert; +var calledInOrder = require("./called-in-order"); +var sinon = require("@sinonjs/referee-sinon").sinon; + +var testObject1 = { + someFunction: function() { + return; + } +}; +var testObject2 = { + otherFunction: function() { + return; + } +}; +var testObject3 = { + thirdFunction: function() { + return; + } +}; + +function testMethod() { + testObject1.someFunction(); + testObject2.otherFunction(); + testObject2.otherFunction(); + testObject2.otherFunction(); + testObject3.thirdFunction(); +} + +describe("calledInOrder", function() { + beforeEach(function() { + sinon.stub(testObject1, "someFunction"); + sinon.stub(testObject2, "otherFunction"); + sinon.stub(testObject3, "thirdFunction"); + testMethod(); + }); + afterEach(function() { + testObject1.someFunction.restore(); + testObject2.otherFunction.restore(); + testObject3.thirdFunction.restore(); + }); + + describe("given single array argument", function() { + describe("when stubs were called in expected order", function() { + it("returns true", function() { + assert.isTrue( + calledInOrder([ + testObject1.someFunction, + testObject2.otherFunction + ]) + ); + assert.isTrue( + calledInOrder([ + testObject1.someFunction, + testObject2.otherFunction, + testObject2.otherFunction, + testObject3.thirdFunction + ]) + ); + }); + }); + + describe("when stubs were called in unexpected order", function() { + it("returns false", function() { + assert.isFalse( + calledInOrder([ + testObject2.otherFunction, + testObject1.someFunction + ]) + ); + assert.isFalse( + calledInOrder([ + testObject2.otherFunction, + testObject1.someFunction, + testObject1.someFunction, + testObject3.thirdFunction + ]) + ); + }); + }); + }); + + describe("given multiple arguments", function() { + describe("when stubs were called in expected order", function() { + it("returns true", function() { + assert.isTrue( + calledInOrder( + testObject1.someFunction, + testObject2.otherFunction + ) + ); + assert.isTrue( + calledInOrder( + testObject1.someFunction, + testObject2.otherFunction, + testObject3.thirdFunction + ) + ); + }); + }); + + describe("when stubs were called in unexpected order", function() { + it("returns false", function() { + assert.isFalse( + calledInOrder( + testObject2.otherFunction, + testObject1.someFunction + ) + ); + assert.isFalse( + calledInOrder( + testObject2.otherFunction, + testObject1.someFunction, + testObject3.thirdFunction + ) + ); + }); + }); + }); +}); diff --git a/node_modules/@sinonjs/commons/lib/class-name.js b/node_modules/@sinonjs/commons/lib/class-name.js new file mode 100644 index 0000000..bcd26ba --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/class-name.js @@ -0,0 +1,27 @@ +"use strict"; + +var functionName = require("./function-name"); + +/** + * Returns a display name for a value from a constructor + * + * @param {object} value A value to examine + * @returns {(string|null)} A string or null + */ +function className(value) { + return ( + (value.constructor && value.constructor.name) || + // The next branch is for IE11 support only: + // Because the name property is not set on the prototype + // of the Function object, we finally try to grab the + // name from its definition. This will never be reached + // in node, so we are not able to test this properly. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name + (typeof value.constructor === "function" && + /* istanbul ignore next */ + functionName(value.constructor)) || + null + ); +} + +module.exports = className; diff --git a/node_modules/@sinonjs/commons/lib/class-name.test.js b/node_modules/@sinonjs/commons/lib/class-name.test.js new file mode 100644 index 0000000..d091506 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/class-name.test.js @@ -0,0 +1,37 @@ +"use strict"; +/* eslint-disable no-empty-function */ + +var assert = require("@sinonjs/referee").assert; +var className = require("./class-name"); + +describe("className", function() { + it("returns the class name of an instance", function() { + // Because eslint-config-sinon disables es6, we can't + // use a class definition here + // https://github.com/sinonjs/eslint-config-sinon/blob/master/index.js + // var instance = new (class TestClass {})(); + var instance = new (function TestClass() {})(); + var name = className(instance); + assert.equals(name, "TestClass"); + }); + + it("returns 'Object' for {}", function() { + var name = className({}); + assert.equals(name, "Object"); + }); + + it("returns null for an object that has no prototype", function() { + var obj = Object.create(null); + var name = className(obj); + assert.equals(name, null); + }); + + it("returns null for an object whose prototype was mangled", function() { + // This is what Node v6 and v7 do for objects returned by querystring.parse() + function MangledObject() {} + MangledObject.prototype = Object.create(null); + var obj = new MangledObject(); + var name = className(obj); + assert.equals(name, null); + }); +}); diff --git a/node_modules/@sinonjs/commons/lib/deprecated.js b/node_modules/@sinonjs/commons/lib/deprecated.js new file mode 100644 index 0000000..ad68cc9 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/deprecated.js @@ -0,0 +1,58 @@ +/* eslint-disable no-console */ +"use strict"; + +/** + * Returns a function that will invoke the supplied function and print a + * deprecation warning to the console each time it is called. + * + * @param {Function} func + * @param {string} msg + * @returns {Function} + */ +exports.wrap = function(func, msg) { + var wrapped = function() { + exports.printWarning(msg); + return func.apply(this, arguments); + }; + if (func.prototype) { + wrapped.prototype = func.prototype; + } + return wrapped; +}; + +/** + * Returns a string which can be supplied to `wrap()` to notify the user that a + * particular part of the sinon API has been deprecated. + * + * @param {string} packageName + * @param {string} funcName + * @returns {string} + */ +exports.defaultMsg = function(packageName, funcName) { + return ( + packageName + + "." + + funcName + + " is deprecated and will be removed from the public API in a future version of " + + packageName + + "." + ); +}; + +/** + * Prints a warning on the console, when it exists + * + * @param {string} msg + * @returns {undefined} + */ +exports.printWarning = function(msg) { + /* istanbul ignore next */ + if (typeof process === "object" && process.emitWarning) { + // Emit Warnings in Node + process.emitWarning(msg); + } else if (console.info) { + console.info(msg); + } else { + console.log(msg); + } +}; diff --git a/node_modules/@sinonjs/commons/lib/deprecated.test.js b/node_modules/@sinonjs/commons/lib/deprecated.test.js new file mode 100644 index 0000000..9034345 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/deprecated.test.js @@ -0,0 +1,100 @@ +/* eslint-disable no-console */ +"use strict"; + +var assert = require("@sinonjs/referee-sinon").assert; +var sinon = require("@sinonjs/referee-sinon").sinon; + +var deprecated = require("./deprecated"); + +var msg = "test"; + +describe("deprecated", function() { + describe("defaultMsg", function() { + it("should return a string", function() { + assert.equals( + deprecated.defaultMsg("sinon", "someFunc"), + "sinon.someFunc is deprecated and will be removed from the public API in a future version of sinon." + ); + }); + }); + + describe("printWarning", function() { + beforeEach(function() { + sinon.replace(process, "emitWarning", sinon.fake()); + }); + + afterEach(sinon.restore); + + describe("when `process.emitWarning` is defined", function() { + it("should call process.emitWarning with a msg", function() { + deprecated.printWarning(msg); + assert.calledOnceWith(process.emitWarning, msg); + }); + }); + + describe("when `process.emitWarning` is undefined", function() { + beforeEach(function() { + sinon.replace(console, "info", sinon.fake()); + sinon.replace(console, "log", sinon.fake()); + process.emitWarning = undefined; + }); + + afterEach(sinon.restore); + + describe("when `console.info` is defined", function() { + it("should call `console.info` with a message", function() { + deprecated.printWarning(msg); + assert.calledOnceWith(console.info, msg); + }); + }); + + describe("when `console.info` is undefined", function() { + it("should call `console.log` with a message", function() { + console.info = undefined; + deprecated.printWarning(msg); + assert.calledOnceWith(console.log, msg); + }); + }); + }); + }); + + describe("wrap", function() { + var method = sinon.fake(); + var wrapped; + + beforeEach(function() { + wrapped = deprecated.wrap(method, msg); + }); + + it("should return a wrapper function", function() { + assert.match(wrapped, sinon.match.func); + }); + + it("should assign the prototype of the passed method", function() { + assert.equals(method.prototype, wrapped.prototype); + }); + + context("when the passed method has falsy prototype", function() { + it("should not be assigned to the wrapped method", function() { + method.prototype = null; + wrapped = deprecated.wrap(method, msg); + assert.match(wrapped.prototype, sinon.match.object); + }); + }); + + context("when invoking the wrapped function", function() { + before(function() { + sinon.replace(deprecated, "printWarning", sinon.fake()); + wrapped({}); + }); + + it("should call `printWarning` before invoking", function() { + assert.calledOnceWith(deprecated.printWarning, msg); + }); + + it("should invoke the passed method with the given arguments", function() { + assert.calledOnceWith(method, {}); + }); + }); + }); +}); diff --git a/node_modules/@sinonjs/commons/lib/every.js b/node_modules/@sinonjs/commons/lib/every.js new file mode 100644 index 0000000..08274b4 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/every.js @@ -0,0 +1,27 @@ +"use strict"; + +/** + * Returns true when fn returns true for all members of obj. + * This is an every implementation that works for all iterables + * + * @param {object} obj + * @param {Function} fn + * @returns {boolean} + */ +module.exports = function every(obj, fn) { + var pass = true; + + try { + // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods + obj.forEach(function() { + if (!fn.apply(this, arguments)) { + // Throwing an error is the only way to break `forEach` + throw new Error(); + } + }); + } catch (e) { + pass = false; + } + + return pass; +}; diff --git a/node_modules/@sinonjs/commons/lib/every.test.js b/node_modules/@sinonjs/commons/lib/every.test.js new file mode 100644 index 0000000..f893d43 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/every.test.js @@ -0,0 +1,41 @@ +"use strict"; + +var assert = require("@sinonjs/referee-sinon").assert; +var sinon = require("@sinonjs/referee-sinon").sinon; +var every = require("./every"); + +describe("util/core/every", function() { + it("returns true when the callback function returns true for every element in an iterable", function() { + var obj = [true, true, true, true]; + var allTrue = every(obj, function(val) { + return val; + }); + + assert(allTrue); + }); + + it("returns false when the callback function returns false for any element in an iterable", function() { + var obj = [true, true, true, false]; + var result = every(obj, function(val) { + return val; + }); + + assert.isFalse(result); + }); + + it("calls the given callback once for each item in an iterable until it returns false", function() { + var iterableOne = [true, true, true, true]; + var iterableTwo = [true, true, false, true]; + var callback = sinon.spy(function(val) { + return val; + }); + + every(iterableOne, callback); + assert.equals(callback.callCount, 4); + + callback.resetHistory(); + + every(iterableTwo, callback); + assert.equals(callback.callCount, 3); + }); +}); diff --git a/node_modules/@sinonjs/commons/lib/function-name.js b/node_modules/@sinonjs/commons/lib/function-name.js new file mode 100644 index 0000000..199b04e --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/function-name.js @@ -0,0 +1,29 @@ +"use strict"; + +/** + * Returns a display name for a function + * + * @param {Function} func + * @returns {string} + */ +module.exports = function functionName(func) { + if (!func) { + return ""; + } + + try { + return ( + func.displayName || + func.name || + // Use function decomposition as a last resort to get function + // name. Does not rely on function decomposition to work - if it + // doesn't debugging will be slightly less informative + // (i.e. toString will say 'spy' rather than 'myFunc'). + (String(func).match(/function ([^\s(]+)/) || [])[1] + ); + } catch (e) { + // Stringify may fail and we might get an exception, as a last-last + // resort fall back to empty string. + return ""; + } +}; diff --git a/node_modules/@sinonjs/commons/lib/function-name.test.js b/node_modules/@sinonjs/commons/lib/function-name.test.js new file mode 100644 index 0000000..6dda3a4 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/function-name.test.js @@ -0,0 +1,76 @@ +"use strict"; + +var jsc = require("jsverify"); +var refute = require("@sinonjs/referee-sinon").refute; + +var functionName = require("./function-name"); + +describe("function-name", function() { + it("should return empty string if func is falsy", function() { + jsc.assertForall("falsy", function(fn) { + return functionName(fn) === ""; + }); + }); + + it("should use displayName by default", function() { + jsc.assertForall("nestring", function(displayName) { + var fn = { displayName: displayName }; + + return functionName(fn) === fn.displayName; + }); + }); + + it("should use name if displayName is not available", function() { + jsc.assertForall("nestring", function(name) { + var fn = { name: name }; + + return functionName(fn) === fn.name; + }); + }); + + it("should fallback to string parsing", function() { + jsc.assertForall("nat", function(naturalNumber) { + var name = "fn" + naturalNumber; + var fn = { + toString: function() { + return "\nfunction " + name; + } + }; + + return functionName(fn) === name; + }); + }); + + it("should not fail when a name cannot be found", function() { + refute.exception(function() { + var fn = { + toString: function() { + return "\nfunction ("; + } + }; + + functionName(fn); + }); + }); + + it("should not fail when toString is undefined", function() { + refute.exception(function() { + functionName(Object.create(null)); + }); + }); + + it("should not fail when toString throws", function() { + refute.exception(function() { + var fn; + try { + // eslint-disable-next-line no-eval + fn = eval("(function*() {})")().constructor; + } catch (e) { + // env doesn't support generators + return; + } + + functionName(fn); + }); + }); +}); diff --git a/node_modules/@sinonjs/commons/lib/global.js b/node_modules/@sinonjs/commons/lib/global.js new file mode 100644 index 0000000..51715a2 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/global.js @@ -0,0 +1,22 @@ +"use strict"; + +/** + * A reference to the global object + * + * @type {object} globalObject + */ +var globalObject; + +/* istanbul ignore else */ +if (typeof global !== "undefined") { + // Node + globalObject = global; +} else if (typeof window !== "undefined") { + // Browser + globalObject = window; +} else { + // WebWorker + globalObject = self; +} + +module.exports = globalObject; diff --git a/node_modules/@sinonjs/commons/lib/global.test.js b/node_modules/@sinonjs/commons/lib/global.test.js new file mode 100644 index 0000000..e49b3da --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/global.test.js @@ -0,0 +1,16 @@ +"use strict"; + +var assert = require("@sinonjs/referee-sinon").assert; +var globalObject = require("./global"); + +describe("global", function() { + before(function() { + if (typeof global === "undefined") { + this.skip(); + } + }); + + it("is same as global", function() { + assert.same(globalObject, global); + }); +}); diff --git a/node_modules/@sinonjs/commons/lib/index.js b/node_modules/@sinonjs/commons/lib/index.js new file mode 100644 index 0000000..5404857 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/index.js @@ -0,0 +1,14 @@ +"use strict"; + +module.exports = { + global: require("./global"), + calledInOrder: require("./called-in-order"), + className: require("./class-name"), + deprecated: require("./deprecated"), + every: require("./every"), + functionName: require("./function-name"), + orderByFirstCall: require("./order-by-first-call"), + prototypes: require("./prototypes"), + typeOf: require("./type-of"), + valueToString: require("./value-to-string") +}; diff --git a/node_modules/@sinonjs/commons/lib/index.test.js b/node_modules/@sinonjs/commons/lib/index.test.js new file mode 100644 index 0000000..cac58a0 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/index.test.js @@ -0,0 +1,29 @@ +"use strict"; + +var assert = require("@sinonjs/referee-sinon").assert; +var index = require("./index"); + +var expectedMethods = [ + "calledInOrder", + "className", + "every", + "functionName", + "orderByFirstCall", + "typeOf", + "valueToString" +]; +var expectedObjectProperties = ["deprecated", "prototypes"]; + +describe("package", function() { + expectedMethods.forEach(function(name) { + it("should export a method named " + name, function() { + assert.isFunction(index[name]); + }); + }); + + expectedObjectProperties.forEach(function(name) { + it("should export an object property named " + name, function() { + assert.isObject(index[name]); + }); + }); +}); diff --git a/node_modules/@sinonjs/commons/lib/order-by-first-call.js b/node_modules/@sinonjs/commons/lib/order-by-first-call.js new file mode 100644 index 0000000..c3d47ed --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/order-by-first-call.js @@ -0,0 +1,36 @@ +"use strict"; + +var sort = require("./prototypes/array").sort; +var slice = require("./prototypes/array").slice; + +/** + * @private + */ +function comparator(a, b) { + // uuid, won't ever be equal + var aCall = a.getCall(0); + var bCall = b.getCall(0); + var aId = (aCall && aCall.callId) || -1; + var bId = (bCall && bCall.callId) || -1; + + return aId < bId ? -1 : 1; +} + +/** + * A Sinon proxy object (fake, spy, stub) + * + * @typedef {object} SinonProxy + * @property {Function} getCall - A method that can return the first call + */ + +/** + * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call + * + * @param {SinonProxy[] | SinonProxy} spies + * @returns {SinonProxy[]} + */ +function orderByFirstCall(spies) { + return sort(slice(spies), comparator); +} + +module.exports = orderByFirstCall; diff --git a/node_modules/@sinonjs/commons/lib/order-by-first-call.test.js b/node_modules/@sinonjs/commons/lib/order-by-first-call.test.js new file mode 100644 index 0000000..485ad43 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/order-by-first-call.test.js @@ -0,0 +1,52 @@ +"use strict"; + +var assert = require("@sinonjs/referee-sinon").assert; +var knuthShuffle = require("knuth-shuffle").knuthShuffle; +var sinon = require("@sinonjs/referee-sinon").sinon; +var orderByFirstCall = require("./order-by-first-call"); + +describe("orderByFirstCall", function() { + it("should order an Array of spies by the callId of the first call, ascending", function() { + // create an array of spies + var spies = [ + sinon.spy(), + sinon.spy(), + sinon.spy(), + sinon.spy(), + sinon.spy(), + sinon.spy() + ]; + + // call all the spies + spies.forEach(function(spy) { + spy(); + }); + + // add a few uncalled spies + spies.push(sinon.spy()); + spies.push(sinon.spy()); + + // randomise the order of the spies + knuthShuffle(spies); + + var sortedSpies = orderByFirstCall(spies); + + assert.equals(sortedSpies.length, spies.length); + + var orderedByFirstCall = sortedSpies.every(function(spy, index) { + if (index + 1 === sortedSpies.length) { + return true; + } + var nextSpy = sortedSpies[index + 1]; + + // uncalled spies should be ordered first + if (!spy.called) { + return true; + } + + return spy.calledImmediatelyBefore(nextSpy); + }); + + assert.isTrue(orderedByFirstCall); + }); +}); diff --git a/node_modules/@sinonjs/commons/lib/prototypes/README.md b/node_modules/@sinonjs/commons/lib/prototypes/README.md new file mode 100644 index 0000000..aff3d91 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/prototypes/README.md @@ -0,0 +1,43 @@ +# Prototypes + +The functions in this folder are to be use for keeping cached references to the built-in prototypes, so that people can't inadvertently break the library by making mistakes in userland. + +See https://github.com/sinonjs/sinon/pull/1523 + +## Without cached references + +```js +// in userland, the library user needs to replace the filter method on +// Array.prototype +var array = [1, 2, 3]; +sinon.replace(array, "filter", sinon.fake.returns(2)); + +// in a sinon module, the library author needs to use the filter method +var someArray = ["a", "b", 42, "c"]; +var answer = filter(someArray, function(v) { + return v === 42; +}); + +console.log(answer); +// => 2 +``` + +## With cached references + +```js +// in userland, the library user needs to replace the filter method on +// Array.prototype +var array = [1, 2, 3]; +sinon.replace(array, "filter", sinon.fake.returns(2)); + +// in a sinon module, the library author needs to use the filter method +// get a reference to the original Array.prototype.filter +var filter = require("@sinonjs/commons").prototypes.array.filter; +var someArray = ["a", "b", 42, "c"]; +var answer = filter(someArray, function(v) { + return v === 42; +}); + +console.log(answer); +// => 42 +``` diff --git a/node_modules/@sinonjs/commons/lib/prototypes/array.js b/node_modules/@sinonjs/commons/lib/prototypes/array.js new file mode 100644 index 0000000..0e332b5 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/prototypes/array.js @@ -0,0 +1,5 @@ +"use strict"; + +var copyPrototype = require("./copy-prototype"); + +module.exports = copyPrototype(Array.prototype); diff --git a/node_modules/@sinonjs/commons/lib/prototypes/copy-prototype.js b/node_modules/@sinonjs/commons/lib/prototypes/copy-prototype.js new file mode 100644 index 0000000..0560a00 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/prototypes/copy-prototype.js @@ -0,0 +1,21 @@ +"use strict"; + +var call = Function.call; + +module.exports = function copyPrototypeMethods(prototype) { + // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods + return Object.getOwnPropertyNames(prototype).reduce(function(result, name) { + // ignore size because it throws from Map + if ( + name !== "size" && + name !== "caller" && + name !== "callee" && + name !== "arguments" && + typeof prototype[name] === "function" + ) { + result[name] = call.bind(prototype[name]); + } + + return result; + }, Object.create(null)); +}; diff --git a/node_modules/@sinonjs/commons/lib/prototypes/function.js b/node_modules/@sinonjs/commons/lib/prototypes/function.js new file mode 100644 index 0000000..28d0cb3 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/prototypes/function.js @@ -0,0 +1,5 @@ +"use strict"; + +var copyPrototype = require("./copy-prototype"); + +module.exports = copyPrototype(Function.prototype); diff --git a/node_modules/@sinonjs/commons/lib/prototypes/index.js b/node_modules/@sinonjs/commons/lib/prototypes/index.js new file mode 100644 index 0000000..6ca7f84 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/prototypes/index.js @@ -0,0 +1,10 @@ +"use strict"; + +module.exports = { + array: require("./array"), + function: require("./function"), + map: require("./map"), + object: require("./object"), + set: require("./set"), + string: require("./string") +}; diff --git a/node_modules/@sinonjs/commons/lib/prototypes/index.test.js b/node_modules/@sinonjs/commons/lib/prototypes/index.test.js new file mode 100644 index 0000000..926f4f1 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/prototypes/index.test.js @@ -0,0 +1,51 @@ +"use strict"; + +var assert = require("@sinonjs/referee-sinon").assert; + +var arrayProto = require("./index").array; +var functionProto = require("./index").function; +var mapProto = require("./index").map; +var objectProto = require("./index").object; +var setProto = require("./index").set; +var stringProto = require("./index").string; + +describe("prototypes", function() { + describe(".array", function() { + verifyProperties(arrayProto, Array); + }); + describe(".function", function() { + verifyProperties(functionProto, Function); + }); + describe(".map", function() { + verifyProperties(mapProto, Map); + }); + describe(".object", function() { + verifyProperties(objectProto, Object); + }); + describe(".set", function() { + verifyProperties(setProto, Set); + }); + describe(".string", function() { + verifyProperties(stringProto, String); + }); +}); + +function verifyProperties(p, origin) { + it("should have all the methods of the origin prototype", function() { + var methodNames = Object.getOwnPropertyNames(origin.prototype).filter( + function(name) { + return ( + name !== "size" && + name !== "caller" && + name !== "callee" && + name !== "arguments" && + typeof origin.prototype[name] === "function" + ); + } + ); + + methodNames.forEach(function(name) { + assert.isTrue(Object.prototype.hasOwnProperty.call(p, name), name); + }); + }); +} diff --git a/node_modules/@sinonjs/commons/lib/prototypes/map.js b/node_modules/@sinonjs/commons/lib/prototypes/map.js new file mode 100644 index 0000000..793d08b --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/prototypes/map.js @@ -0,0 +1,5 @@ +"use strict"; + +var copyPrototype = require("./copy-prototype"); + +module.exports = copyPrototype(Map.prototype); diff --git a/node_modules/@sinonjs/commons/lib/prototypes/object.js b/node_modules/@sinonjs/commons/lib/prototypes/object.js new file mode 100644 index 0000000..5b18b56 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/prototypes/object.js @@ -0,0 +1,5 @@ +"use strict"; + +var copyPrototype = require("./copy-prototype"); + +module.exports = copyPrototype(Object.prototype); diff --git a/node_modules/@sinonjs/commons/lib/prototypes/set.js b/node_modules/@sinonjs/commons/lib/prototypes/set.js new file mode 100644 index 0000000..b5ade92 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/prototypes/set.js @@ -0,0 +1,5 @@ +"use strict"; + +var copyPrototype = require("./copy-prototype"); + +module.exports = copyPrototype(Set.prototype); diff --git a/node_modules/@sinonjs/commons/lib/prototypes/string.js b/node_modules/@sinonjs/commons/lib/prototypes/string.js new file mode 100644 index 0000000..edc905e --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/prototypes/string.js @@ -0,0 +1,5 @@ +"use strict"; + +var copyPrototype = require("./copy-prototype"); + +module.exports = copyPrototype(String.prototype); diff --git a/node_modules/@sinonjs/commons/lib/type-of.js b/node_modules/@sinonjs/commons/lib/type-of.js new file mode 100644 index 0000000..97a0bb9 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/type-of.js @@ -0,0 +1,13 @@ +"use strict"; + +var type = require("type-detect"); + +/** + * Returns the lower-case result of running type from type-detect on the value + * + * @param {*} value + * @returns {string} + */ +module.exports = function typeOf(value) { + return type(value).toLowerCase(); +}; diff --git a/node_modules/@sinonjs/commons/lib/type-of.test.js b/node_modules/@sinonjs/commons/lib/type-of.test.js new file mode 100644 index 0000000..5fcfc74 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/type-of.test.js @@ -0,0 +1,51 @@ +"use strict"; + +var assert = require("@sinonjs/referee-sinon").assert; +var typeOf = require("./type-of"); + +describe("typeOf", function() { + it("returns boolean", function() { + assert.equals(typeOf(false), "boolean"); + }); + + it("returns string", function() { + assert.equals(typeOf("Sinon.JS"), "string"); + }); + + it("returns number", function() { + assert.equals(typeOf(123), "number"); + }); + + it("returns object", function() { + assert.equals(typeOf({}), "object"); + }); + + it("returns function", function() { + assert.equals( + typeOf(function() { + return undefined; + }), + "function" + ); + }); + + it("returns undefined", function() { + assert.equals(typeOf(undefined), "undefined"); + }); + + it("returns null", function() { + assert.equals(typeOf(null), "null"); + }); + + it("returns array", function() { + assert.equals(typeOf([]), "array"); + }); + + it("returns regexp", function() { + assert.equals(typeOf(/.*/), "regexp"); + }); + + it("returns date", function() { + assert.equals(typeOf(new Date()), "date"); + }); +}); diff --git a/node_modules/@sinonjs/commons/lib/value-to-string.js b/node_modules/@sinonjs/commons/lib/value-to-string.js new file mode 100644 index 0000000..fb14782 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/value-to-string.js @@ -0,0 +1,17 @@ +"use strict"; + +/** + * Returns a string representation of the value + * + * @param {*} value + * @returns {string} + */ +function valueToString(value) { + if (value && value.toString) { + // eslint-disable-next-line @sinonjs/no-prototype-methods/no-prototype-methods + return value.toString(); + } + return String(value); +} + +module.exports = valueToString; diff --git a/node_modules/@sinonjs/commons/lib/value-to-string.test.js b/node_modules/@sinonjs/commons/lib/value-to-string.test.js new file mode 100644 index 0000000..5cae501 --- /dev/null +++ b/node_modules/@sinonjs/commons/lib/value-to-string.test.js @@ -0,0 +1,20 @@ +"use strict"; + +var assert = require("@sinonjs/referee-sinon").assert; +var valueToString = require("./value-to-string"); + +describe("util/core/valueToString", function() { + it("returns string representation of an object", function() { + var obj = {}; + + assert.equals(valueToString(obj), obj.toString()); + }); + + it("returns 'null' for literal null'", function() { + assert.equals(valueToString(null), "null"); + }); + + it("returns 'undefined' for literal undefined", function() { + assert.equals(valueToString(undefined), "undefined"); + }); +}); diff --git a/node_modules/@sinonjs/commons/package.json b/node_modules/@sinonjs/commons/package.json new file mode 100644 index 0000000..f0e6c14 --- /dev/null +++ b/node_modules/@sinonjs/commons/package.json @@ -0,0 +1,67 @@ +{ + "name": "@sinonjs/commons", + "version": "1.8.3", + "description": "Simple functions shared among the sinon end user libraries", + "main": "lib/index.js", + "types": "./types/index.d.ts", + "scripts": { + "build": "rm -rf types && tsc", + "lint": "eslint .", + "precommit": "lint-staged", + "test": "mocha --recursive -R dot \"lib/**/*.test.js\"", + "test-check-coverage": "npm run test-coverage && nyc check-coverage --branches 100 --functions 100 --lines 100", + "test-coverage": "nyc --reporter text --reporter html --reporter lcovonly npm run test", + "prepublishOnly": "npm run build", + "prettier:check": "prettier --check '**/*.{js,css,md}'", + "prettier:write": "prettier --write '**/*.{js,css,md}'", + "preversion": "npm run test-check-coverage", + "version": "changes --commits --footer", + "postversion": "git push --follow-tags && npm publish" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sinonjs/commons.git" + }, + "files": [ + "lib", + "types" + ], + "author": "", + "license": "BSD-3-Clause", + "bugs": { + "url": "https://github.com/sinonjs/commons/issues" + }, + "homepage": "https://github.com/sinonjs/commons#readme", + "lint-staged": { + "*.{js,css,md}": "prettier --check", + "*.js": "eslint" + }, + "devDependencies": { + "@sinonjs/eslint-plugin-no-prototype-methods": "^0.1.0", + "@sinonjs/referee-sinon": "7.0.2", + "@studio/changes": "^2.0.0", + "eslint": "^6.1.0", + "eslint-config-prettier": "^6.3.0", + "eslint-config-sinon": "^4.0.0", + "eslint-plugin-ie11": "^1.0.0", + "eslint-plugin-jsdoc": "^22.1.0", + "eslint-plugin-mocha": "^6.1.1", + "eslint-plugin-prettier": "^3.0.0", + "husky": "4.2.3", + "jsverify": "0.8.4", + "knuth-shuffle": "^1.0.8", + "lint-staged": "10.1.1", + "mocha": "7.1.0", + "nyc": "15.0.0", + "prettier": "^1.14.3", + "typescript": "^4.1.3" + }, + "dependencies": { + "type-detect": "4.0.8" + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + } +} diff --git a/node_modules/@sinonjs/commons/types/called-in-order.d.ts b/node_modules/@sinonjs/commons/types/called-in-order.d.ts new file mode 100644 index 0000000..1a4508b --- /dev/null +++ b/node_modules/@sinonjs/commons/types/called-in-order.d.ts @@ -0,0 +1,36 @@ +export = calledInOrder; +/** + * A Sinon proxy object (fake, spy, stub) + * + * @typedef {object} SinonProxy + * @property {Function} calledBefore - A method that determines if this proxy was called before another one + * @property {string} id - Some id + * @property {number} callCount - Number of times this proxy has been called + */ +/** + * Returns true when the spies have been called in the order they were supplied in + * + * @param {SinonProxy[] | SinonProxy} spies An array of proxies, or several proxies as arguments + * @returns {boolean} true when spies are called in order, false otherwise + */ +declare function calledInOrder(spies: SinonProxy[] | SinonProxy, ...args: any[]): boolean; +declare namespace calledInOrder { + export { SinonProxy }; +} +/** + * A Sinon proxy object (fake, spy, stub) + */ +type SinonProxy = { + /** + * - A method that determines if this proxy was called before another one + */ + calledBefore: Function; + /** + * - Some id + */ + id: string; + /** + * - Number of times this proxy has been called + */ + callCount: number; +}; diff --git a/node_modules/@sinonjs/commons/types/class-name.d.ts b/node_modules/@sinonjs/commons/types/class-name.d.ts new file mode 100644 index 0000000..df3687b --- /dev/null +++ b/node_modules/@sinonjs/commons/types/class-name.d.ts @@ -0,0 +1,8 @@ +export = className; +/** + * Returns a display name for a value from a constructor + * + * @param {object} value A value to examine + * @returns {(string|null)} A string or null + */ +declare function className(value: object): (string | null); diff --git a/node_modules/@sinonjs/commons/types/deprecated.d.ts b/node_modules/@sinonjs/commons/types/deprecated.d.ts new file mode 100644 index 0000000..81a35bf --- /dev/null +++ b/node_modules/@sinonjs/commons/types/deprecated.d.ts @@ -0,0 +1,3 @@ +export function wrap(func: Function, msg: string): Function; +export function defaultMsg(packageName: string, funcName: string): string; +export function printWarning(msg: string): undefined; diff --git a/node_modules/@sinonjs/commons/types/every.d.ts b/node_modules/@sinonjs/commons/types/every.d.ts new file mode 100644 index 0000000..bcfa64e --- /dev/null +++ b/node_modules/@sinonjs/commons/types/every.d.ts @@ -0,0 +1,2 @@ +declare function _exports(obj: object, fn: Function): boolean; +export = _exports; diff --git a/node_modules/@sinonjs/commons/types/function-name.d.ts b/node_modules/@sinonjs/commons/types/function-name.d.ts new file mode 100644 index 0000000..f27d519 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/function-name.d.ts @@ -0,0 +1,2 @@ +declare function _exports(func: Function): string; +export = _exports; diff --git a/node_modules/@sinonjs/commons/types/global.d.ts b/node_modules/@sinonjs/commons/types/global.d.ts new file mode 100644 index 0000000..0f54a63 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/global.d.ts @@ -0,0 +1,7 @@ +export = globalObject; +/** + * A reference to the global object + * + * @type {object} globalObject + */ +declare var globalObject: object; diff --git a/node_modules/@sinonjs/commons/types/index.d.ts b/node_modules/@sinonjs/commons/types/index.d.ts new file mode 100644 index 0000000..7d675b1 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/index.d.ts @@ -0,0 +1,17 @@ +export const global: any; +export const calledInOrder: typeof import("./called-in-order"); +export const className: typeof import("./class-name"); +export const deprecated: typeof import("./deprecated"); +export const every: (obj: any, fn: Function) => boolean; +export const functionName: (func: Function) => string; +export const orderByFirstCall: typeof import("./order-by-first-call"); +export const prototypes: { + array: any; + function: any; + map: any; + object: any; + set: any; + string: any; +}; +export const typeOf: (value: any) => string; +export const valueToString: typeof import("./value-to-string"); diff --git a/node_modules/@sinonjs/commons/types/order-by-first-call.d.ts b/node_modules/@sinonjs/commons/types/order-by-first-call.d.ts new file mode 100644 index 0000000..a9a6037 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/order-by-first-call.d.ts @@ -0,0 +1,26 @@ +export = orderByFirstCall; +/** + * A Sinon proxy object (fake, spy, stub) + * + * @typedef {object} SinonProxy + * @property {Function} getCall - A method that can return the first call + */ +/** + * Sorts an array of SinonProxy instances (fake, spy, stub) by their first call + * + * @param {SinonProxy[] | SinonProxy} spies + * @returns {SinonProxy[]} + */ +declare function orderByFirstCall(spies: SinonProxy[] | SinonProxy): SinonProxy[]; +declare namespace orderByFirstCall { + export { SinonProxy }; +} +/** + * A Sinon proxy object (fake, spy, stub) + */ +type SinonProxy = { + /** + * - A method that can return the first call + */ + getCall: Function; +}; diff --git a/node_modules/@sinonjs/commons/types/prototypes/array.d.ts b/node_modules/@sinonjs/commons/types/prototypes/array.d.ts new file mode 100644 index 0000000..1cce635 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/prototypes/array.d.ts @@ -0,0 +1,2 @@ +declare const _exports: any; +export = _exports; diff --git a/node_modules/@sinonjs/commons/types/prototypes/copy-prototype.d.ts b/node_modules/@sinonjs/commons/types/prototypes/copy-prototype.d.ts new file mode 100644 index 0000000..1479b93 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/prototypes/copy-prototype.d.ts @@ -0,0 +1,2 @@ +declare function _exports(prototype: any): any; +export = _exports; diff --git a/node_modules/@sinonjs/commons/types/prototypes/function.d.ts b/node_modules/@sinonjs/commons/types/prototypes/function.d.ts new file mode 100644 index 0000000..1cce635 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/prototypes/function.d.ts @@ -0,0 +1,2 @@ +declare const _exports: any; +export = _exports; diff --git a/node_modules/@sinonjs/commons/types/prototypes/index.d.ts b/node_modules/@sinonjs/commons/types/prototypes/index.d.ts new file mode 100644 index 0000000..0026d6c --- /dev/null +++ b/node_modules/@sinonjs/commons/types/prototypes/index.d.ts @@ -0,0 +1,7 @@ +export declare const array: any; +declare const _function: any; +export { _function as function }; +export declare const map: any; +export declare const object: any; +export declare const set: any; +export declare const string: any; diff --git a/node_modules/@sinonjs/commons/types/prototypes/map.d.ts b/node_modules/@sinonjs/commons/types/prototypes/map.d.ts new file mode 100644 index 0000000..1cce635 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/prototypes/map.d.ts @@ -0,0 +1,2 @@ +declare const _exports: any; +export = _exports; diff --git a/node_modules/@sinonjs/commons/types/prototypes/object.d.ts b/node_modules/@sinonjs/commons/types/prototypes/object.d.ts new file mode 100644 index 0000000..1cce635 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/prototypes/object.d.ts @@ -0,0 +1,2 @@ +declare const _exports: any; +export = _exports; diff --git a/node_modules/@sinonjs/commons/types/prototypes/set.d.ts b/node_modules/@sinonjs/commons/types/prototypes/set.d.ts new file mode 100644 index 0000000..1cce635 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/prototypes/set.d.ts @@ -0,0 +1,2 @@ +declare const _exports: any; +export = _exports; diff --git a/node_modules/@sinonjs/commons/types/prototypes/string.d.ts b/node_modules/@sinonjs/commons/types/prototypes/string.d.ts new file mode 100644 index 0000000..1cce635 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/prototypes/string.d.ts @@ -0,0 +1,2 @@ +declare const _exports: any; +export = _exports; diff --git a/node_modules/@sinonjs/commons/types/type-of.d.ts b/node_modules/@sinonjs/commons/types/type-of.d.ts new file mode 100644 index 0000000..fc72887 --- /dev/null +++ b/node_modules/@sinonjs/commons/types/type-of.d.ts @@ -0,0 +1,2 @@ +declare function _exports(value: any): string; +export = _exports; diff --git a/node_modules/@sinonjs/commons/types/value-to-string.d.ts b/node_modules/@sinonjs/commons/types/value-to-string.d.ts new file mode 100644 index 0000000..19b086c --- /dev/null +++ b/node_modules/@sinonjs/commons/types/value-to-string.d.ts @@ -0,0 +1,8 @@ +export = valueToString; +/** + * Returns a string representation of the value + * + * @param {*} value + * @returns {string} + */ +declare function valueToString(value: any): string; diff --git a/node_modules/@sinonjs/fake-timers/CHANGELOG.md b/node_modules/@sinonjs/fake-timers/CHANGELOG.md new file mode 100644 index 0000000..ecf4d99 --- /dev/null +++ b/node_modules/@sinonjs/fake-timers/CHANGELOG.md @@ -0,0 +1,469 @@ + +9.1.2 / 2022-04-13 +================== + + * Prohibit faking of faked timers (#426) + +9.1.1 / 2022-03-05 +================== + + * fix(timer.refresh): should just change `callAt` (#425) + +9.1.0 / 2022-02-03 +================== + + * add hasRef (#419) + +9.0.0 / 2022-01-28 +================== + + * Breaking: remove Node 10 from running tests + * chore(ci): do not hard code node versions (#417) + * chore: test on node 17 (#416) + * fix global performance node 16 (#412) + * Bump node-fetch from 2.6.1 to 2.6.7 (#414) + * Bump cached-path-relative from 1.0.2 to 1.1.0 (#413) + * Clarify async usage (#411) + * Faking performance when not present should throw an error (and minor changes) - fix for #374 (#400) + * Add performance to config.toFake + +8.1.0 / 2021-11-03 +================== + + * Add native timer clean-up behavior (#407) + * give a hint about how to get type defs (#405) + +8.0.1 / 2021-09-25 +================== + + * fix: handle missing stack when throwing recursion errors (#401) + +8.0.0 / 2021-09-15 +================== + + * Remove generated typescript definitions. If you use this package with TypeScript, install `@types/sinonjs__fake-timers` after upgrading (#386) + * Issue 390 implicit dependencies on faking interval (#391) + * replace var with const/let (#392) + * Retry - Add stack trace to code recursively scheduling timers #325 (#375) + +7.1.2 / 2021-05-28 +================== + + * Fix #382 by making config fields optional (#383) + * Fix #347 : Support util.promisify + +7.1.1 / 2021-05-27 +================== + + * Fix JSDoc for createClock + +7.1.0 / 2021-05-20 +================== + + * Remove Safari from Sauce Lab (ref #380) + * Bump hosted-git-info from 2.6.0 to 2.8.9 + * Bump handlebars from 4.7.6 to 4.7.7 + * Bump lodash from 4.17.19 to 4.17.21 + * Add in latest Safari and evergreen Edge + * Drop IE11 and Safari 9 + * chore: add type tests (#373) + * remove constructor types + * use globalThis to avoid conflicts + * Update yargs-parser + * Update mkdirp + * Upgrade jsdom + * Upgrade mochify to latest + * Upgrade Mocha to latest + * Bump y18n from 4.0.0 to 4.0.1 + * make config optional + * add a bunch more types + +7.0.5 / 2021-04-11 +================== + + * Fix up some clock types in JSDoc (becomes `.d.ts`) (#370) + * Fix refresh arguments forwarding (#369) + +7.0.4 / 2021-04-08 +================== + + * Fix usage with TypeScript + +7.0.3 / 2021-03-02 +================== + + * Removing the use of eval in Node.js (#331) + * Drop Node 8 + * Add docs about typings (#357) + +7.0.2 / 2021-01-18 +================== + + * Make config options optional in TypeScript defs (#354) + +7.0.1 / 2021-01-14 +================== + + * Update README section about browser use + +7.0.0 / 2021-01-12 +================== + + * Remove bundle from package. If you're loading `fake-timers` via + script tag, you'll now have to provide your own bundled version + * Add .d.ts files to package + * Revert "Add stack trace to code recursively scheduling timers" (#338) + * Remove unnecessary durations and use globals + * Support timeout.refresh in node environments + * Fix #319: Error message changed to TypeError + * Fix #319: The use of 'eval' has been removed + * Fix #304: clearTimeout clears setInterval and clearInterval clears setTimeout + * Remove config.target (#318) + + +6.0.1 / 2020-03-24 +================== + + * Support util.promisify in Node (#223) + +6.0.0 / 2020-02-04 +================== + + * Rename project to `@sinonjs/fake-timers` + +5.1.2 / 2019-12-19 +================== + + * Use global from `@sinonjs/commons` + * Fix setSystemTime affects hrtime if its called multiple times. + * Test coverage: use nyc + +5.1.1 / 2019-10-21 +================== + + * Fix global ReferenceError (#273) + +5.1.0 / 2019-10-14 +================== + + * Upgrade lolex with async versions of most calls + +5.0.1 / 2019-10-10 +================== + + * Upgrade eslint, add prettier + * Use `--no-detect-globals` to bundle and test lolex (#270) + +5.0.0 / 2019-10-07 +================== + + * Avoid installing setImmediate in unsupported environments + * fix #246: non-constructor Date() should return a string + +4.2.0 / 2019-08-04 +================== + + * Fix support for replacing the JSDOM performance field + +4.1.0 / 2019-06-04 +================== + + * Fix crash on Bash version 3 (macOS) + * Support hrtime.bigint() + * fix: count microtasks in countTimers + * Return empty arrays for performance.getEntries, other relevant methods + +4.0.1 / 2019-04-17 +================== + + * Remove sinon: added by mistake + +4.0.0 / 2019-04-17 +================== + + * Drop support for IE9 and IE10: link to supported browsers in README + * No more ExperimentalWarnings in Node environment for queueMicrotask() if it's not used in user's code + +3.1.0 / 2019-02-11 +================== + + * default timeout set to 50ms + * first implementation of requestIdleCallback and cancelIdleCallback + * fixed accidentally performance.now() -> x.now() replacement + * added queueMicrotask + +3.0.0 / 2018-10-08 +================== + + * Add countTimers method + * Disallow negative ticks (breaking API change!) + * Avoid exposing hrNow + * Fix #207 - round-off errors in `hrtime` + * Truncate sub-nanosecond values for `hrtime` + * Truncate sub-millisceond values for `Date.now()` + +v2.7.5 / 2018-09-19 +================== + + * fix: handle floating point in hrtime (#210) + * fix: reset high resolution timer on clock.reset (#209) + * Add an error when creating a clock with no Date object (#205) + +v2.7.4 / 2018-09-05 +================== + + * performance.mark related fixes for failing Safari, IE 10 and IE 11 tests + +v2.7.3 / 2018-09-05 +================== + + * Fix for #200: TypeError on performance.mark + +v2.7.2 / 2018-09-04 +================== + + * fix(setInterval): parse `timeout` arg to integer (#202) + * Upgrade insecure dependencies with npm audit fix + +v2.7.1 / 2018-07-06 +================== + * Fix performance replacement on iOS 9.3 + +v2.7.0 / 2018-05-25 +================== + + * reset clock to start + * check Performance exists before touching it + +v2.6.0 / 2018-05-16 +================== + + * Fix `reset` and document it publicly Clear microtick jobs and set now to 0 in reset (#179) + * Access Date on `_global` (#178) + +v2.5.0 / 2018-05-13 +================== + + * feat: respect loopLimit in runMicrotasks (#172) + * assign performance as a property, not as a function + +v2.4.2 / 2018-05-11 +=================== + * Upgrade Mochify to v5.6 (#162) fixed #170 + * Access `Performance` via `_global` (#168) + +v2.4.1 / 2018-05-08 +================== + + * fix: handle negative infinity timeout (#165) + +v2.4.0 / 2018-05-08 +================== + + * Add `withGlobal` export + * expose runMicrotasks + * Fix that performance.mark is undefined after timer install + +v2.3.2 / 2018-01-29 +================== + +* Add files section to package.json to avoid unnecessary package bloat #154 +* Add missing functions in default `toFake` #150 + +v2.3.1 / 2017-11-22 +================== + + * bugfix for a setTimeout() or setSystemTime() within a nextTick() call. (#145) + +v2.3.0 / 2017-11-08 +================== + + * Stops leak of (request|cancel)AnimationFrame into global scope. (#143) + * return timers on uninstall + +v2.2.0 / 2017-11-07 +================== + + * Add support for requestAnimationFrame + * fix negative timeout bug + +v2.1.3 / 2017-10-03 +================== + + * add module entry point (#133) + +v2.1.2 / 2017-07-25 +================== + + * - does not fake process.nextTick by default - added .idea folder to .gitignore - fixed documentation - added clock teardowns in tests + * overflowing the timer correctly (issue #67) + +v2.1.1 / 2017-07-19 +================== + + * support passing parameters in nextTick (fixes #122) + +v2.1.0 / 2017-07-18 +================== + + * Throw error on incorrect install use (#112) + * Add support for process.nextTick + * lolex can now attach itself to the system timers and automatically ad… (#102) + * update hrtime when an interval ticks + +v2.0.0 / 2017-07-13 +================== + + * New install() signature + * Add support for performance.now (#106) + * Fix issue with tick(): setSystemClock then throw + * Update old dependencies + * Added support to automatically increment time (#85) + * Changed internal uninstall method signature + +v1.6.0 / 2017-02-25 +=================== + + * Use common Sinon.JS eslint config + * Allow install to be called with date object + * Remove wrapper function + * Fixed typo in clock.runAll error + +v1.5.2 / 2016-11-10 +=================== + + * Upgrade mocha to latest + * Only overwrite globals when running in IE + +1.5.1 / 2016-07-26 +================== + + * Fix setInterval() behavior with string times + * Incorporate test from PR #65 + * Fix issue #59: context object required 'process' + * fixed a case where runAll was called and there are no timers (#70) + * Correct the clear{Interval|Timeout|Immediate} error message when calling `set*` for a different type of timer. + * Lots of minor changes to tooling and the build process + +v1.5.0 / 2016-05-18 +=================== + + * 1.5.0 + * Check for existence of `process` before using it + * Run to last existing timer + * Add runAll method to run timers until empty + * Turn off Sauce Labs tests for pull requests + * Add tests demonstrating that a fake Date could be created with one argument as a String since this string is in a format recognized by the Date.parse() method. + * Run test-cloud on Travis + * Add process.hrtime() + * Add bithound badge to Readme.md + * Make Travis also run tests in node 4.2 + * Update jslint, referee, sinon, browserify, mocha, mochify + * Rename src/lolex.js to src/lolex-src.js to avoid bithound ignoring it + * Add .bithoundrc + +v1.4.0 / 2015-12-11 +=================== + + * 1.4.0 + * Remove BASH syntax in lint script + * correct test descriptions to match the tests + * correct parseTime() error message so it matches behavior + * don't run test-cloud as part of npm test + * doc: full API reference + * doc: update 'Running tests' section + * doc: update 'Faking the native timers' section + * doc: remove requestAnimationFrame + * Implement clock.next() + * Run lint in CI + * Fix jslint errors + +v1.3.2 / 2015-09-22 +=================== + + * 1.3.2 + * Fix for breaking shimmed setImmediate + +v1.3.1 / 2015-08-20 +=================== + + * Remove error whos reason is no longer accurate + +v1.3.0 / 2015-08-19 +=================== + + * 1.3.0 + * Throw exception on wrong use of clearXYZ() + * Fix for Sinon.JS issue #808 :add setSystemTime() function + * Fix for Sinon.JS issue #766: clearTimeout() no longer clears Immediate/Interval and vice versa + * Update Readme.md to point to LICENSE file + * Fix error in readme about running tests + * Fix for warning about SPDX license format on npm install + +v1.2.2 / 2015-07-22 +=================== + + * 1.2.2 + * Fixing lint mistake + * Update travis to use node@0.12 + * Fix complaint about missing fake setImmediate + * Use license in package.json + +v1.2.1 / 2015-01-06 +=================== + + * New build + * Dodge JSLint... + * Up version + * Proper fix for writable globals in IE + * Make timers writable in old IEs + +v1.2.0 / 2014-12-12 +=================== + + * 1.2.0 + * Fix Sinon.JS issue 624 + * Lint the test files also + * Add .jslintrc + * Delay setImmediate if it is during tick call + * Add test case + * Test behaviour of hasOwnProperty beforehand + * Compare now() with delta + * Use undefined for defined predicate + * Put setImmediate in toFake list + * Capture clock instance for uninstall + * Restore commented out tests + * Add JSLint verification to test + * Configure Travis to run tests in node 0.10.x + * Add .editorconfig + * Fail when faking Date but not setTimeout/setInterval + +v1.1.10 / 2014-11-14 +==================== + + * 1.1.0 Fixes setImmediate problems + * Rely on `timer` initialization to null + * Timer assembly occurs at addTimer callsites + * Sort immediate timers before non-immediate + * Add createdAt to timers + * Sort timers by multiple criteria, not just callAt + * Refactor firstTimerInRange + * Rename `timeouts` property to `timers` + * addTimer is options-driven + +v1.0.0 / 2014-11-12 +=================== + + * Add built file for browsers + * Fix URL + * Don't run tests that require global.__proto__ on IE 9 and IE 10 + * Add "bundle" script to create standalone UMD bundle with browserify + * Float with new test framework versions + * Remove redundant module prefix + * Let Browserify set "global" for us + * Change test framework from Buster to Mocha and Mochify + * Make timer functions independent on `this` + * Change APIs according to Readme + * Change clock-creating interface + * Change Github paths + * Basically working extraction from Sinon.JS diff --git a/node_modules/@sinonjs/fake-timers/LICENSE b/node_modules/@sinonjs/fake-timers/LICENSE new file mode 100644 index 0000000..eb84755 --- /dev/null +++ b/node_modules/@sinonjs/fake-timers/LICENSE @@ -0,0 +1,11 @@ +Copyright (c) 2010-2014, Christian Johansen, christian@cjohansen.no. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. 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. + +3. Neither the name of the copyright holder 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 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. \ No newline at end of file diff --git a/node_modules/@sinonjs/fake-timers/README.md b/node_modules/@sinonjs/fake-timers/README.md new file mode 100644 index 0000000..22f40d9 --- /dev/null +++ b/node_modules/@sinonjs/fake-timers/README.md @@ -0,0 +1,351 @@ +# `@sinonjs/fake-timers` + +[![codecov](https://codecov.io/gh/sinonjs/fake-timers/branch/main/graph/badge.svg)](https://codecov.io/gh/sinonjs/fake-timers) +Contributor Covenant + +JavaScript implementation of the timer APIs; `setTimeout`, `clearTimeout`, `setImmediate`, `clearImmediate`, `setInterval`, `clearInterval`, `requestAnimationFrame`, `cancelAnimationFrame`, `requestIdleCallback`, and `cancelIdleCallback`, along with a clock instance that controls the flow of time. FakeTimers also provides a `Date` implementation that gets its time from the clock. + +In addition in browser environment `@sinonjs/fake-timers` provides a `performance` implementation that gets its time from the clock. In Node environments FakeTimers provides a `nextTick` implementation that is synchronized with the clock - and a `process.hrtime` shim that works with the clock. + +`@sinonjs/fake-timers` can be used to simulate passing time in automated tests and other +situations where you want the scheduling semantics, but don't want to actually +wait. + +`@sinonjs/fake-timers` is extracted from [Sinon.JS](https://github.com/sinonjs/sinon.js) and targets the [same runtimes](https://sinonjs.org/releases/latest/#supported-runtimes). + +## Autocomplete, IntelliSense and TypeScript definitions + +Version 7 introduced JSDoc to the codebase. This should provide autocomplete and type suggestions in supporting IDEs. If you need more elaborate type support, TypeScript definitions for the Sinon projects are independently maintained by the Definitely Types community: + +``` +npm install -D @types/sinonjs__fake-timers +``` + +## Installation + +`@sinonjs/fake-timers` can be used in both Node and browser environments. Installation is as easy as + +```sh +npm install @sinonjs/fake-timers +``` + +If you want to use `@sinonjs/fake-timers` in a browser you can either build your own bundle or use [Skypack](https://www.skypack.dev). + +## Usage + +To use `@sinonjs/fake-timers`, create a new clock, schedule events on it using the timer +functions and pass time using the `tick` method. + +```js +// In the browser distribution, a global `FakeTimers` is already available +var FakeTimers = require("@sinonjs/fake-timers"); +var clock = FakeTimers.createClock(); + +clock.setTimeout(function () { + console.log( + "The poblano is a mild chili pepper originating in the state of Puebla, Mexico." + ); +}, 15); + +// ... + +clock.tick(15); +``` + +Upon executing the last line, an interesting fact about the +[Poblano](https://en.wikipedia.org/wiki/Poblano) will be printed synchronously to +the screen. If you want to simulate asynchronous behavior, please see the `async` function variants (eg `clock.tick(time)` vs `await clock.tickAsync(time)`). + +The `next`, `runAll`, `runToFrame`, and `runToLast` methods are available to advance the clock. See the +API Reference for more details. + +### Faking the native timers + +When using `@sinonjs/fake-timers` to test timers, you will most likely want to replace the native +timers such that calling `setTimeout` actually schedules a callback with your +clock instance, not the browser's internals. + +Calling `install` with no arguments achieves this. You can call `uninstall` +later to restore things as they were again. + +```js +// In the browser distribution, a global `FakeTimers` is already available +var FakeTimers = require("@sinonjs/fake-timers"); + +var clock = FakeTimers.install(); +// Equivalent to +// var clock = FakeTimers.install(typeof global !== "undefined" ? global : window); + +setTimeout(fn, 15); // Schedules with clock.setTimeout + +clock.uninstall(); +// setTimeout is restored to the native implementation +``` + +To hijack timers in another context pass it to the `install` method. + +```js +var FakeTimers = require("@sinonjs/fake-timers"); +var context = { + setTimeout: setTimeout, // By default context.setTimeout uses the global setTimeout +}; +var clock = FakeTimers.withGlobal(context).install(); + +context.setTimeout(fn, 15); // Schedules with clock.setTimeout + +clock.uninstall(); +// context.setTimeout is restored to the original implementation +``` + +Usually you want to install the timers onto the global object, so call `install` +without arguments. + +#### Automatically incrementing mocked time + +FakeTimers supports the possibility to attach the faked timers to any change +in the real system time. This means that there is no need to `tick()` the +clock in a situation where you won't know **when** to call `tick()`. + +Please note that this is achieved using the original setImmediate() API at a certain +configurable interval `config.advanceTimeDelta` (default: 20ms). Meaning time would +be incremented every 20ms, not in real time. + +An example would be: + +```js +var FakeTimers = require("@sinonjs/fake-timers"); +var clock = FakeTimers.install({ + shouldAdvanceTime: true, + advanceTimeDelta: 40, +}); + +setTimeout(() => { + console.log("this just timed out"); //executed after 40ms +}, 30); + +setImmediate(() => { + console.log("not so immediate"); //executed after 40ms +}); + +setTimeout(() => { + console.log("this timed out after"); //executed after 80ms + clock.uninstall(); +}, 50); +``` + +## API Reference + +### `var clock = FakeTimers.createClock([now[, loopLimit]])` + +Creates a clock. The default +[epoch](https://en.wikipedia.org/wiki/Epoch_%28reference_date%29) is `0`. + +The `now` argument may be a number (in milliseconds) or a Date object. + +The `loopLimit` argument sets the maximum number of timers that will be run when calling `runAll()` before assuming that we have an infinite loop and throwing an error. The default is `1000`. + +### `var clock = FakeTimers.install([config])` + +Installs FakeTimers using the specified config (otherwise with epoch `0` on the global scope). The following configuration options are available + +| Parameter | Type | Default | Description | +| -------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `config.now` | Number/Date | 0 | installs FakeTimers with the specified unix epoch | +| `config.toFake` | String[] | ["setTimeout", "clearTimeout", "setImmediate", "clearImmediate","setInterval", "clearInterval", "Date", "requestAnimationFrame", "cancelAnimationFrame", "requestIdleCallback", "cancelIdleCallback", "hrtime", "performance"] | an array with explicit function names (or objects, in the case of "performance") to hijack. _When not set, FakeTimers will automatically fake all methods **except** `nextTick`_ e.g., `FakeTimers.install({ toFake: ["setTimeout","nextTick"]})` will fake only `setTimeout` and `nextTick` | +| `config.loopLimit` | Number | 1000 | the maximum number of timers that will be run when calling runAll() | +| `config.shouldAdvanceTime` | Boolean | false | tells FakeTimers to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by 20ms for every 20ms change in the real system time) | +| `config.advanceTimeDelta` | Number | 20 | relevant only when using with `shouldAdvanceTime: true`. increment mocked time by `advanceTimeDelta` ms every `advanceTimeDelta` ms change in the real system time. | +| `config.shouldClearNativeTimers` | Boolean | false | tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their respective handlers. These are not cleared by default, leading to potentially unexpected behavior if timers existed prior to installing FakeTimers. | + +### `var id = clock.setTimeout(callback, timeout)` + +Schedules the callback to be fired once `timeout` milliseconds have ticked by. + +In Node.js `setTimeout` returns a timer object. FakeTimers will do the same, however +its `ref()` and `unref()` methods have no effect. + +In browsers a timer ID is returned. + +### `clock.clearTimeout(id)` + +Clears the timer given the ID or timer object, as long as it was created using +`setTimeout`. + +### `var id = clock.setInterval(callback, timeout)` + +Schedules the callback to be fired every time `timeout` milliseconds have ticked +by. + +In Node.js `setInterval` returns a timer object. FakeTimers will do the same, however +its `ref()` and `unref()` methods have no effect. + +In browsers a timer ID is returned. + +### `clock.clearInterval(id)` + +Clears the timer given the ID or timer object, as long as it was created using +`setInterval`. + +### `var id = clock.setImmediate(callback)` + +Schedules the callback to be fired once `0` milliseconds have ticked by. Note +that you'll still have to call `clock.tick()` for the callback to fire. If +called during a tick the callback won't fire until `1` millisecond has ticked +by. + +In Node.js `setImmediate` returns a timer object. FakeTimers will do the same, +however its `ref()` and `unref()` methods have no effect. + +In browsers a timer ID is returned. + +### `clock.clearImmediate(id)` + +Clears the timer given the ID or timer object, as long as it was created using +`setImmediate`. + +### `clock.requestAnimationFrame(callback)` + +Schedules the callback to be fired on the next animation frame, which runs every +16 ticks. Returns an `id` which can be used to cancel the callback. This is +available in both browser & node environments. + +### `clock.cancelAnimationFrame(id)` + +Cancels the callback scheduled by the provided id. + +### `clock.requestIdleCallback(callback[, timeout])` + +Queued the callback to be fired during idle periods to perform background and low priority work on the main event loop. Callbacks which have a timeout option will be fired no later than time in milliseconds. Returns an `id` which can be used to cancel the callback. + +### `clock.cancelIdleCallback(id)` + +Cancels the callback scheduled by the provided id. + +### `clock.countTimers()` + +Returns the number of waiting timers. This can be used to assert that a test +finishes without leaking any timers. + +### `clock.hrtime(prevTime?)` + +Only available in Node.js, mimicks process.hrtime(). + +### `clock.nextTick(callback)` + +Only available in Node.js, mimics `process.nextTick` to enable completely synchronous testing flows. + +### `clock.performance.now()` + +Only available in browser environments, mimicks performance.now(). + +### `clock.tick(time)` / `await clock.tickAsync(time)` + +Advance the clock, firing callbacks if necessary. `time` may be the number of +milliseconds to advance the clock by or a human-readable string. Valid string +formats are `"08"` for eight seconds, `"01:00"` for one minute and `"02:34:10"` +for two hours, 34 minutes and ten seconds. + +The `tickAsync()` will also break the event loop, allowing any scheduled promise +callbacks to execute _before_ running the timers. + +### `clock.next()` / `await clock.nextAsync()` + +Advances the clock to the the moment of the first scheduled timer, firing it. + +The `nextAsync()` will also break the event loop, allowing any scheduled promise +callbacks to execute _before_ running the timers. + +### `clock.reset()` + +Removes all timers and ticks without firing them, and sets `now` to `config.now` +that was provided to `FakeTimers.install` or to `0` if `config.now` was not provided. +Useful to reset the state of the clock without having to `uninstall` and `install` it. + +### `clock.runAll()` / `await clock.runAllAsync()` + +This runs all pending timers until there are none remaining. If new timers are added while it is executing they will be run as well. + +This makes it easier to run asynchronous tests to completion without worrying about the number of timers they use, or the delays in those timers. + +It runs a maximum of `loopLimit` times after which it assumes there is an infinite loop of timers and throws an error. + +The `runAllAsync()` will also break the event loop, allowing any scheduled promise +callbacks to execute _before_ running the timers. + +### `clock.runMicrotasks()` + +This runs all pending microtasks scheduled with `nextTick` but none of the timers and is mostly useful for libraries using FakeTimers underneath and for running `nextTick` items without any timers. + +### `clock.runToFrame()` + +Advances the clock to the next frame, firing all scheduled animation frame callbacks, +if any, for that frame as well as any other timers scheduled along the way. + +### `clock.runToLast()` / `await clock.runToLastAsync()` + +This takes note of the last scheduled timer when it is run, and advances the +clock to that time firing callbacks as necessary. + +If new timers are added while it is executing they will be run only if they +would occur before this time. + +This is useful when you want to run a test to completion, but the test recursively +sets timers that would cause `runAll` to trigger an infinite loop warning. + +The `runToLastAsync()` will also break the event loop, allowing any scheduled promise +callbacks to execute _before_ running the timers. + +### `clock.setSystemTime([now])` + +This simulates a user changing the system clock while your program is running. +It affects the current time but it does not in itself cause e.g. timers to fire; +they will fire exactly as they would have done without the call to +setSystemTime(). + +### `clock.uninstall()` + +Restores the original methods of the native timers or the methods on the object +that was passed to `FakeTimers.withGlobal` + +### `Date` + +Implements the `Date` object but using the clock to provide the correct time. + +### `Performance` + +Implements the `now` method of the [`Performance`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now) object but using the clock to provide the correct time. Only available in environments that support the Performance object (browsers mostly). + +### `FakeTimers.withGlobal` + +In order to support creating clocks based on separate or sandboxed environments (such as JSDOM), FakeTimers exports a factory method which takes single argument `global`, which it inspects to figure out what to mock and what features to support. When invoking this function with a global, you will get back an object with `timers`, `createClock` and `install` - same as the regular FakeTimers exports only based on the passed in global instead of the global environment. + +## Running tests + +FakeTimers has a comprehensive test suite. If you're thinking of contributing bug +fixes or suggesting new features, you need to make sure you have not broken any +tests. You are also expected to add tests for any new behavior. + +### On node: + +```sh +npm test +``` + +Or, if you prefer more verbose output: + +``` +$(npm bin)/mocha ./test/fake-timers-test.js +``` + +### In the browser + +[Mochify](https://github.com/mantoni/mochify.js) is used to run the tests in +PhantomJS. Make sure you have `phantomjs` installed. Then: + +```sh +npm test-headless +``` + +## License + +BSD 3-clause "New" or "Revised" License (see LICENSE file) diff --git a/node_modules/@sinonjs/fake-timers/package.json b/node_modules/@sinonjs/fake-timers/package.json new file mode 100644 index 0000000..b857ff9 --- /dev/null +++ b/node_modules/@sinonjs/fake-timers/package.json @@ -0,0 +1,71 @@ +{ + "name": "@sinonjs/fake-timers", + "description": "Fake JavaScript timers", + "version": "9.1.2", + "homepage": "https://github.com/sinonjs/fake-timers", + "author": "Christian Johansen", + "repository": { + "type": "git", + "url": "https://github.com/sinonjs/fake-timers.git" + }, + "bugs": { + "mail": "christian@cjohansen.no", + "url": "https://github.com/sinonjs/fake-timers/issues" + }, + "license": "BSD-3-Clause", + "scripts": { + "lint": "eslint .", + "test-node": "mocha --timeout 200 test/ integration-test/ -R dot --check-leaks", + "test-headless": "mochify --no-detect-globals --timeout=10000", + "test-check-coverage": "npm run test-coverage && nyc check-coverage", + "test-cloud": "mochify --wd --no-detect-globals --timeout=10000", + "test-coverage": "nyc --all --reporter text --reporter html --reporter lcovonly npm run test-node", + "test": "npm run test-node && npm run test-headless", + "prettier:check": "prettier --check '**/*.{js,css,md}'", + "prettier:write": "prettier --write '**/*.{js,css,md}'", + "preversion": "./scripts/preversion.sh", + "version": "./scripts/version.sh", + "postversion": "./scripts/postversion.sh" + }, + "lint-staged": { + "*.{js,css,md}": "prettier --check", + "*.js": "eslint" + }, + "files": [ + "src/" + ], + "devDependencies": { + "@sinonjs/eslint-config": "4.0.2", + "@sinonjs/referee-sinon": "6.0.1", + "eslint-config-prettier": "8.3.0", + "eslint-plugin-prettier": "3.4.1", + "husky": "4.2.1", + "jsdom": "16.5.2", + "lint-staged": "10.0.7", + "mocha": "9.2.0", + "mochify": "7.0.0", + "nyc": "14.1.1", + "prettier": "2.2.1" + }, + "main": "./src/fake-timers-src.js", + "dependencies": { + "@sinonjs/commons": "^1.7.0" + }, + "husky": { + "hooks": { + "pre-commit": "npm run lint" + } + }, + "nyc": { + "branches": 85, + "lines": 92, + "functions": 92, + "statements": 92, + "exclude": [ + "**/*-test.js", + "coverage/**", + "types/**", + "fake-timers.js" + ] + } +} diff --git a/node_modules/@sinonjs/fake-timers/src/fake-timers-src.js b/node_modules/@sinonjs/fake-timers/src/fake-timers-src.js new file mode 100644 index 0000000..a8f69fc --- /dev/null +++ b/node_modules/@sinonjs/fake-timers/src/fake-timers-src.js @@ -0,0 +1,1766 @@ +"use strict"; + +const globalObject = require("@sinonjs/commons").global; + +/** + * @typedef {object} IdleDeadline + * @property {boolean} didTimeout - whether or not the callback was called before reaching the optional timeout + * @property {function():number} timeRemaining - a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period + */ + +/** + * Queues a function to be called during a browser's idle periods + * + * @callback RequestIdleCallback + * @param {function(IdleDeadline)} callback + * @param {{timeout: number}} options - an options object + * @returns {number} the id + */ + +/** + * @callback NextTick + * @param {VoidVarArgsFunc} callback - the callback to run + * @param {...*} arguments - optional arguments to call the callback with + * @returns {void} + */ + +/** + * @callback SetImmediate + * @param {VoidVarArgsFunc} callback - the callback to run + * @param {...*} arguments - optional arguments to call the callback with + * @returns {NodeImmediate} + */ + +/** + * @callback VoidVarArgsFunc + * @param {...*} callback - the callback to run + * @returns {void} + */ + +/** + * @typedef RequestAnimationFrame + * @property {function(number):void} requestAnimationFrame + * @returns {number} - the id + */ + +/** + * @typedef Performance + * @property {function(): number} now + */ + +/* eslint-disable jsdoc/require-property-description */ +/** + * @typedef {object} Clock + * @property {number} now - the current time + * @property {Date} Date - the Date constructor + * @property {number} loopLimit - the maximum number of timers before assuming an infinite loop + * @property {RequestIdleCallback} requestIdleCallback + * @property {function(number):void} cancelIdleCallback + * @property {setTimeout} setTimeout + * @property {clearTimeout} clearTimeout + * @property {NextTick} nextTick + * @property {queueMicrotask} queueMicrotask + * @property {setInterval} setInterval + * @property {clearInterval} clearInterval + * @property {SetImmediate} setImmediate + * @property {function(NodeImmediate):void} clearImmediate + * @property {function():number} countTimers + * @property {RequestAnimationFrame} requestAnimationFrame + * @property {function(number):void} cancelAnimationFrame + * @property {function():void} runMicrotasks + * @property {function(string | number): number} tick + * @property {function(string | number): Promise} tickAsync + * @property {function(): number} next + * @property {function(): Promise} nextAsync + * @property {function(): number} runAll + * @property {function(): number} runToFrame + * @property {function(): Promise} runAllAsync + * @property {function(): number} runToLast + * @property {function(): Promise} runToLastAsync + * @property {function(): void} reset + * @property {function(number | Date): void} setSystemTime + * @property {Performance} performance + * @property {function(number[]): number[]} hrtime - process.hrtime (legacy) + * @property {function(): void} uninstall Uninstall the clock. + * @property {Function[]} methods - the methods that are faked + * @property {boolean} [shouldClearNativeTimers] inherited from config + */ +/* eslint-enable jsdoc/require-property-description */ + +/** + * Configuration object for the `install` method. + * + * @typedef {object} Config + * @property {number|Date} [now] a number (in milliseconds) or a Date object (default epoch) + * @property {string[]} [toFake] names of the methods that should be faked. + * @property {number} [loopLimit] the maximum number of timers that will be run when calling runAll() + * @property {boolean} [shouldAdvanceTime] tells FakeTimers to increment mocked time automatically (default false) + * @property {number} [advanceTimeDelta] increment mocked time every <> ms (default: 20ms) + * @property {boolean} [shouldClearNativeTimers] forwards clear timer calls to native functions if they are not fakes (default: false) + */ + +/* eslint-disable jsdoc/require-property-description */ +/** + * The internal structure to describe a scheduled fake timer + * + * @typedef {object} Timer + * @property {Function} func + * @property {*[]} args + * @property {number} delay + * @property {number} callAt + * @property {number} createdAt + * @property {boolean} immediate + * @property {number} id + * @property {Error} [error] + */ + +/** + * A Node timer + * + * @typedef {object} NodeImmediate + * @property {function(): boolean} hasRef + * @property {function(): NodeImmediate} ref + * @property {function(): NodeImmediate} unref + */ +/* eslint-enable jsdoc/require-property-description */ + +/* eslint-disable complexity */ + +/** + * Mocks available features in the specified global namespace. + * + * @param {*} _global Namespace to mock (e.g. `window`) + * @returns {FakeTimers} + */ +function withGlobal(_global) { + const userAgent = _global.navigator && _global.navigator.userAgent; + const isRunningInIE = userAgent && userAgent.indexOf("MSIE ") > -1; + const maxTimeout = Math.pow(2, 31) - 1; //see https://heycam.github.io/webidl/#abstract-opdef-converttoint + const idCounterStart = 1e12; // arbitrarily large number to avoid collisions with native timer IDs + const NOOP = function () { + return undefined; + }; + const NOOP_ARRAY = function () { + return []; + }; + const timeoutResult = _global.setTimeout(NOOP, 0); + const addTimerReturnsObject = typeof timeoutResult === "object"; + const hrtimePresent = + _global.process && typeof _global.process.hrtime === "function"; + const hrtimeBigintPresent = + hrtimePresent && typeof _global.process.hrtime.bigint === "function"; + const nextTickPresent = + _global.process && typeof _global.process.nextTick === "function"; + const utilPromisify = _global.process && require("util").promisify; + const performancePresent = + _global.performance && typeof _global.performance.now === "function"; + const hasPerformancePrototype = + _global.Performance && + (typeof _global.Performance).match(/^(function|object)$/); + const hasPerformanceConstructorPrototype = + _global.performance && + _global.performance.constructor && + _global.performance.constructor.prototype; + const queueMicrotaskPresent = _global.hasOwnProperty("queueMicrotask"); + const requestAnimationFramePresent = + _global.requestAnimationFrame && + typeof _global.requestAnimationFrame === "function"; + const cancelAnimationFramePresent = + _global.cancelAnimationFrame && + typeof _global.cancelAnimationFrame === "function"; + const requestIdleCallbackPresent = + _global.requestIdleCallback && + typeof _global.requestIdleCallback === "function"; + const cancelIdleCallbackPresent = + _global.cancelIdleCallback && + typeof _global.cancelIdleCallback === "function"; + const setImmediatePresent = + _global.setImmediate && typeof _global.setImmediate === "function"; + + // Make properties writable in IE, as per + // https://www.adequatelygood.com/Replacing-setTimeout-Globally.html + /* eslint-disable no-self-assign */ + if (isRunningInIE) { + _global.setTimeout = _global.setTimeout; + _global.clearTimeout = _global.clearTimeout; + _global.setInterval = _global.setInterval; + _global.clearInterval = _global.clearInterval; + _global.Date = _global.Date; + } + + // setImmediate is not a standard function + // avoid adding the prop to the window object if not present + if (setImmediatePresent) { + _global.setImmediate = _global.setImmediate; + _global.clearImmediate = _global.clearImmediate; + } + /* eslint-enable no-self-assign */ + + _global.clearTimeout(timeoutResult); + + const NativeDate = _global.Date; + let uniqueTimerId = idCounterStart; + + /** + * @param {number} num + * @returns {boolean} + */ + function isNumberFinite(num) { + if (Number.isFinite) { + return Number.isFinite(num); + } + + return isFinite(num); + } + + let isNearInfiniteLimit = false; + + /** + * @param {Clock} clock + * @param {number} i + */ + function checkIsNearInfiniteLimit(clock, i) { + if (clock.loopLimit && i === clock.loopLimit - 1) { + isNearInfiniteLimit = true; + } + } + + /** + * + */ + function resetIsNearInfiniteLimit() { + isNearInfiniteLimit = false; + } + + /** + * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into + * number of milliseconds. This is used to support human-readable strings passed + * to clock.tick() + * + * @param {string} str + * @returns {number} + */ + function parseTime(str) { + if (!str) { + return 0; + } + + const strings = str.split(":"); + const l = strings.length; + let i = l; + let ms = 0; + let parsed; + + if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { + throw new Error( + "tick only understands numbers, 'm:s' and 'h:m:s'. Each part must be two digits" + ); + } + + while (i--) { + parsed = parseInt(strings[i], 10); + + if (parsed >= 60) { + throw new Error(`Invalid time ${str}`); + } + + ms += parsed * Math.pow(60, l - i - 1); + } + + return ms * 1000; + } + + /** + * Get the decimal part of the millisecond value as nanoseconds + * + * @param {number} msFloat the number of milliseconds + * @returns {number} an integer number of nanoseconds in the range [0,1e6) + * + * Example: nanoRemainer(123.456789) -> 456789 + */ + function nanoRemainder(msFloat) { + const modulo = 1e6; + const remainder = (msFloat * 1e6) % modulo; + const positiveRemainder = + remainder < 0 ? remainder + modulo : remainder; + + return Math.floor(positiveRemainder); + } + + /** + * Used to grok the `now` parameter to createClock. + * + * @param {Date|number} epoch the system time + * @returns {number} + */ + function getEpoch(epoch) { + if (!epoch) { + return 0; + } + if (typeof epoch.getTime === "function") { + return epoch.getTime(); + } + if (typeof epoch === "number") { + return epoch; + } + throw new TypeError("now should be milliseconds since UNIX epoch"); + } + + /** + * @param {number} from + * @param {number} to + * @param {Timer} timer + * @returns {boolean} + */ + function inRange(from, to, timer) { + return timer && timer.callAt >= from && timer.callAt <= to; + } + + /** + * @param {Clock} clock + * @param {Timer} job + */ + function getInfiniteLoopError(clock, job) { + const infiniteLoopError = new Error( + `Aborting after running ${clock.loopLimit} timers, assuming an infinite loop!` + ); + + if (!job.error) { + return infiniteLoopError; + } + + // pattern never matched in Node + const computedTargetPattern = /target\.*[<|(|[].*?[>|\]|)]\s*/; + let clockMethodPattern = new RegExp( + String(Object.keys(clock).join("|")) + ); + + if (addTimerReturnsObject) { + // node.js environment + clockMethodPattern = new RegExp( + `\\s+at (Object\\.)?(?:${Object.keys(clock).join("|")})\\s+` + ); + } + + let matchedLineIndex = -1; + job.error.stack.split("\n").some(function (line, i) { + // If we've matched a computed target line (e.g. setTimeout) then we + // don't need to look any further. Return true to stop iterating. + const matchedComputedTarget = line.match(computedTargetPattern); + /* istanbul ignore if */ + if (matchedComputedTarget) { + matchedLineIndex = i; + return true; + } + + // If we've matched a clock method line, then there may still be + // others further down the trace. Return false to keep iterating. + const matchedClockMethod = line.match(clockMethodPattern); + if (matchedClockMethod) { + matchedLineIndex = i; + return false; + } + + // If we haven't matched anything on this line, but we matched + // previously and set the matched line index, then we can stop. + // If we haven't matched previously, then we should keep iterating. + return matchedLineIndex >= 0; + }); + + const stack = `${infiniteLoopError}\n${job.type || "Microtask"} - ${ + job.func.name || "anonymous" + }\n${job.error.stack + .split("\n") + .slice(matchedLineIndex + 1) + .join("\n")}`; + + try { + Object.defineProperty(infiniteLoopError, "stack", { + value: stack, + }); + } catch (e) { + // noop + } + + return infiniteLoopError; + } + + /** + * @param {Date} target + * @param {Date} source + * @returns {Date} the target after modifications + */ + function mirrorDateProperties(target, source) { + let prop; + for (prop in source) { + if (source.hasOwnProperty(prop)) { + target[prop] = source[prop]; + } + } + + // set special now implementation + if (source.now) { + target.now = function now() { + return target.clock.now; + }; + } else { + delete target.now; + } + + // set special toSource implementation + if (source.toSource) { + target.toSource = function toSource() { + return source.toSource(); + }; + } else { + delete target.toSource; + } + + // set special toString implementation + target.toString = function toString() { + return source.toString(); + }; + + target.prototype = source.prototype; + target.parse = source.parse; + target.UTC = source.UTC; + target.prototype.toUTCString = source.prototype.toUTCString; + target.isFake = true; + + return target; + } + + //eslint-disable-next-line jsdoc/require-jsdoc + function createDate() { + /** + * @param {number} year + * @param {number} month + * @param {number} date + * @param {number} hour + * @param {number} minute + * @param {number} second + * @param {number} ms + * + * @returns {Date} + */ + function ClockDate(year, month, date, hour, minute, second, ms) { + // the Date constructor called as a function, ref Ecma-262 Edition 5.1, section 15.9.2. + // This remains so in the 10th edition of 2019 as well. + if (!(this instanceof ClockDate)) { + return new NativeDate(ClockDate.clock.now).toString(); + } + + // if Date is called as a constructor with 'new' keyword + // Defensive and verbose to avoid potential harm in passing + // explicit undefined when user does not pass argument + switch (arguments.length) { + case 0: + return new NativeDate(ClockDate.clock.now); + case 1: + return new NativeDate(year); + case 2: + return new NativeDate(year, month); + case 3: + return new NativeDate(year, month, date); + case 4: + return new NativeDate(year, month, date, hour); + case 5: + return new NativeDate(year, month, date, hour, minute); + case 6: + return new NativeDate( + year, + month, + date, + hour, + minute, + second + ); + default: + return new NativeDate( + year, + month, + date, + hour, + minute, + second, + ms + ); + } + } + + return mirrorDateProperties(ClockDate, NativeDate); + } + + //eslint-disable-next-line jsdoc/require-jsdoc + function enqueueJob(clock, job) { + // enqueues a microtick-deferred task - ecma262/#sec-enqueuejob + if (!clock.jobs) { + clock.jobs = []; + } + clock.jobs.push(job); + } + + //eslint-disable-next-line jsdoc/require-jsdoc + function runJobs(clock) { + // runs all microtick-deferred tasks - ecma262/#sec-runjobs + if (!clock.jobs) { + return; + } + for (let i = 0; i < clock.jobs.length; i++) { + const job = clock.jobs[i]; + job.func.apply(null, job.args); + + checkIsNearInfiniteLimit(clock, i); + if (clock.loopLimit && i > clock.loopLimit) { + throw getInfiniteLoopError(clock, job); + } + } + resetIsNearInfiniteLimit(); + clock.jobs = []; + } + + /** + * @param {Clock} clock + * @param {Timer} timer + * @returns {number} id of the created timer + */ + function addTimer(clock, timer) { + if (timer.func === undefined) { + throw new Error("Callback must be provided to timer calls"); + } + + if (addTimerReturnsObject) { + // Node.js environment + if (typeof timer.func !== "function") { + throw new TypeError( + `[ERR_INVALID_CALLBACK]: Callback must be a function. Received ${ + timer.func + } of type ${typeof timer.func}` + ); + } + } + + if (isNearInfiniteLimit) { + timer.error = new Error(); + } + + timer.type = timer.immediate ? "Immediate" : "Timeout"; + + if (timer.hasOwnProperty("delay")) { + if (typeof timer.delay !== "number") { + timer.delay = parseInt(timer.delay, 10); + } + + if (!isNumberFinite(timer.delay)) { + timer.delay = 0; + } + timer.delay = timer.delay > maxTimeout ? 1 : timer.delay; + timer.delay = Math.max(0, timer.delay); + } + + if (timer.hasOwnProperty("interval")) { + timer.type = "Interval"; + timer.interval = timer.interval > maxTimeout ? 1 : timer.interval; + } + + if (timer.hasOwnProperty("animation")) { + timer.type = "AnimationFrame"; + timer.animation = true; + } + + if (timer.hasOwnProperty("idleCallback")) { + timer.type = "IdleCallback"; + timer.idleCallback = true; + } + + if (!clock.timers) { + clock.timers = {}; + } + + timer.id = uniqueTimerId++; + timer.createdAt = clock.now; + timer.callAt = + clock.now + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0)); + + clock.timers[timer.id] = timer; + + if (addTimerReturnsObject) { + const res = { + refed: true, + ref: function () { + this.refed = true; + return res; + }, + unref: function () { + this.refed = false; + return res; + }, + hasRef: function () { + return this.refed; + }, + refresh: function () { + timer.callAt = + clock.now + + (parseInt(timer.delay) || (clock.duringTick ? 1 : 0)); + + // it _might_ have been removed, but if not the assignment is perfectly fine + clock.timers[timer.id] = timer; + + return res; + }, + [Symbol.toPrimitive]: function () { + return timer.id; + }, + }; + return res; + } + + return timer.id; + } + + /* eslint consistent-return: "off" */ + /** + * Timer comparitor + * + * @param {Timer} a + * @param {Timer} b + * @returns {number} + */ + function compareTimers(a, b) { + // Sort first by absolute timing + if (a.callAt < b.callAt) { + return -1; + } + if (a.callAt > b.callAt) { + return 1; + } + + // Sort next by immediate, immediate timers take precedence + if (a.immediate && !b.immediate) { + return -1; + } + if (!a.immediate && b.immediate) { + return 1; + } + + // Sort next by creation time, earlier-created timers take precedence + if (a.createdAt < b.createdAt) { + return -1; + } + if (a.createdAt > b.createdAt) { + return 1; + } + + // Sort next by id, lower-id timers take precedence + if (a.id < b.id) { + return -1; + } + if (a.id > b.id) { + return 1; + } + + // As timer ids are unique, no fallback `0` is necessary + } + + /** + * @param {Clock} clock + * @param {number} from + * @param {number} to + * + * @returns {Timer} + */ + function firstTimerInRange(clock, from, to) { + const timers = clock.timers; + let timer = null; + let id, isInRange; + + for (id in timers) { + if (timers.hasOwnProperty(id)) { + isInRange = inRange(from, to, timers[id]); + + if ( + isInRange && + (!timer || compareTimers(timer, timers[id]) === 1) + ) { + timer = timers[id]; + } + } + } + + return timer; + } + + /** + * @param {Clock} clock + * @returns {Timer} + */ + function firstTimer(clock) { + const timers = clock.timers; + let timer = null; + let id; + + for (id in timers) { + if (timers.hasOwnProperty(id)) { + if (!timer || compareTimers(timer, timers[id]) === 1) { + timer = timers[id]; + } + } + } + + return timer; + } + + /** + * @param {Clock} clock + * @returns {Timer} + */ + function lastTimer(clock) { + const timers = clock.timers; + let timer = null; + let id; + + for (id in timers) { + if (timers.hasOwnProperty(id)) { + if (!timer || compareTimers(timer, timers[id]) === -1) { + timer = timers[id]; + } + } + } + + return timer; + } + + /** + * @param {Clock} clock + * @param {Timer} timer + */ + function callTimer(clock, timer) { + if (typeof timer.interval === "number") { + clock.timers[timer.id].callAt += timer.interval; + } else { + delete clock.timers[timer.id]; + } + + if (typeof timer.func === "function") { + timer.func.apply(null, timer.args); + } else { + /* eslint no-eval: "off" */ + const eval2 = eval; + (function () { + eval2(timer.func); + })(); + } + } + + /** + * Gets clear handler name for a given timer type + * + * @param {string} ttype + */ + function getClearHandler(ttype) { + if (ttype === "IdleCallback" || ttype === "AnimationFrame") { + return `cancel${ttype}`; + } + return `clear${ttype}`; + } + + /** + * Gets schedule handler name for a given timer type + * + * @param {string} ttype + */ + function getScheduleHandler(ttype) { + if (ttype === "IdleCallback" || ttype === "AnimationFrame") { + return `request${ttype}`; + } + return `set${ttype}`; + } + + /** + * Creates an anonymous function to warn only once + */ + function createWarnOnce() { + let calls = 0; + return function (msg) { + // eslint-disable-next-line + !calls++ && console.warn(msg); + }; + } + const warnOnce = createWarnOnce(); + + /** + * @param {Clock} clock + * @param {number} timerId + * @param {string} ttype + */ + function clearTimer(clock, timerId, ttype) { + if (!timerId) { + // null appears to be allowed in most browsers, and appears to be + // relied upon by some libraries, like Bootstrap carousel + return; + } + + if (!clock.timers) { + clock.timers = {}; + } + + // in Node, the ID is stored as the primitive value for `Timeout` objects + // for `Immediate` objects, no ID exists, so it gets coerced to NaN + const id = Number(timerId); + + if (Number.isNaN(id) || id < idCounterStart) { + const handlerName = getClearHandler(ttype); + + if (clock.shouldClearNativeTimers === true) { + const nativeHandler = clock[`_${handlerName}`]; + return typeof nativeHandler === "function" + ? nativeHandler(timerId) + : undefined; + } + warnOnce( + `FakeTimers: ${handlerName} was invoked to clear a native timer instead of one created by this library.` + + "\nTo automatically clean-up native timers, use `shouldClearNativeTimers`." + ); + } + + if (clock.timers.hasOwnProperty(id)) { + // check that the ID matches a timer of the correct type + const timer = clock.timers[id]; + if ( + timer.type === ttype || + (timer.type === "Timeout" && ttype === "Interval") || + (timer.type === "Interval" && ttype === "Timeout") + ) { + delete clock.timers[id]; + } else { + const clear = getClearHandler(ttype); + const schedule = getScheduleHandler(timer.type); + throw new Error( + `Cannot clear timer: timer created with ${schedule}() but cleared with ${clear}()` + ); + } + } + } + + /** + * @param {Clock} clock + * @param {Config} config + * @returns {Timer[]} + */ + function uninstall(clock, config) { + let method, i, l; + const installedHrTime = "_hrtime"; + const installedNextTick = "_nextTick"; + + for (i = 0, l = clock.methods.length; i < l; i++) { + method = clock.methods[i]; + if (method === "hrtime" && _global.process) { + _global.process.hrtime = clock[installedHrTime]; + } else if (method === "nextTick" && _global.process) { + _global.process.nextTick = clock[installedNextTick]; + } else if (method === "performance") { + const originalPerfDescriptor = Object.getOwnPropertyDescriptor( + clock, + `_${method}` + ); + if ( + originalPerfDescriptor && + originalPerfDescriptor.get && + !originalPerfDescriptor.set + ) { + Object.defineProperty( + _global, + method, + originalPerfDescriptor + ); + } else if (originalPerfDescriptor.configurable) { + _global[method] = clock[`_${method}`]; + } + } else { + if (_global[method] && _global[method].hadOwnProperty) { + _global[method] = clock[`_${method}`]; + } else { + try { + delete _global[method]; + } catch (ignore) { + /* eslint no-empty: "off" */ + } + } + } + } + + if (config.shouldAdvanceTime === true) { + _global.clearInterval(clock.attachedInterval); + } + + // Prevent multiple executions which will completely remove these props + clock.methods = []; + + // return pending timers, to enable checking what timers remained on uninstall + if (!clock.timers) { + return []; + } + return Object.keys(clock.timers).map(function mapper(key) { + return clock.timers[key]; + }); + } + + /** + * @param {object} target the target containing the method to replace + * @param {string} method the keyname of the method on the target + * @param {Clock} clock + */ + function hijackMethod(target, method, clock) { + clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call( + target, + method + ); + clock[`_${method}`] = target[method]; + + if (method === "Date") { + const date = mirrorDateProperties(clock[method], target[method]); + target[method] = date; + } else if (method === "performance") { + const originalPerfDescriptor = Object.getOwnPropertyDescriptor( + target, + method + ); + // JSDOM has a read only performance field so we have to save/copy it differently + if ( + originalPerfDescriptor && + originalPerfDescriptor.get && + !originalPerfDescriptor.set + ) { + Object.defineProperty( + clock, + `_${method}`, + originalPerfDescriptor + ); + + const perfDescriptor = Object.getOwnPropertyDescriptor( + clock, + method + ); + Object.defineProperty(target, method, perfDescriptor); + } else { + target[method] = clock[method]; + } + } else { + target[method] = function () { + return clock[method].apply(clock, arguments); + }; + + Object.defineProperties( + target[method], + Object.getOwnPropertyDescriptors(clock[method]) + ); + } + + target[method].clock = clock; + } + + /** + * @param {Clock} clock + * @param {number} advanceTimeDelta + */ + function doIntervalTick(clock, advanceTimeDelta) { + clock.tick(advanceTimeDelta); + } + + /** + * @typedef {object} Timers + * @property {setTimeout} setTimeout + * @property {clearTimeout} clearTimeout + * @property {setInterval} setInterval + * @property {clearInterval} clearInterval + * @property {Date} Date + * @property {SetImmediate=} setImmediate + * @property {function(NodeImmediate): void=} clearImmediate + * @property {function(number[]):number[]=} hrtime + * @property {NextTick=} nextTick + * @property {Performance=} performance + * @property {RequestAnimationFrame=} requestAnimationFrame + * @property {boolean=} queueMicrotask + * @property {function(number): void=} cancelAnimationFrame + * @property {RequestIdleCallback=} requestIdleCallback + * @property {function(number): void=} cancelIdleCallback + */ + + /** @type {Timers} */ + const timers = { + setTimeout: _global.setTimeout, + clearTimeout: _global.clearTimeout, + setInterval: _global.setInterval, + clearInterval: _global.clearInterval, + Date: _global.Date, + }; + + if (setImmediatePresent) { + timers.setImmediate = _global.setImmediate; + timers.clearImmediate = _global.clearImmediate; + } + + if (hrtimePresent) { + timers.hrtime = _global.process.hrtime; + } + + if (nextTickPresent) { + timers.nextTick = _global.process.nextTick; + } + + if (performancePresent) { + timers.performance = _global.performance; + } + + if (requestAnimationFramePresent) { + timers.requestAnimationFrame = _global.requestAnimationFrame; + } + + if (queueMicrotaskPresent) { + timers.queueMicrotask = true; + } + + if (cancelAnimationFramePresent) { + timers.cancelAnimationFrame = _global.cancelAnimationFrame; + } + + if (requestIdleCallbackPresent) { + timers.requestIdleCallback = _global.requestIdleCallback; + } + + if (cancelIdleCallbackPresent) { + timers.cancelIdleCallback = _global.cancelIdleCallback; + } + + const originalSetTimeout = _global.setImmediate || _global.setTimeout; + + /** + * @param {Date|number} [start] the system time - non-integer values are floored + * @param {number} [loopLimit] maximum number of timers that will be run when calling runAll() + * @returns {Clock} + */ + function createClock(start, loopLimit) { + // eslint-disable-next-line no-param-reassign + start = Math.floor(getEpoch(start)); + // eslint-disable-next-line no-param-reassign + loopLimit = loopLimit || 1000; + let nanos = 0; + const adjustedSystemTime = [0, 0]; // [millis, nanoremainder] + + if (NativeDate === undefined) { + throw new Error( + "The global scope doesn't have a `Date` object" + + " (see https://github.com/sinonjs/sinon/issues/1852#issuecomment-419622780)" + ); + } + + const clock = { + now: start, + Date: createDate(), + loopLimit: loopLimit, + }; + + clock.Date.clock = clock; + + //eslint-disable-next-line jsdoc/require-jsdoc + function getTimeToNextFrame() { + return 16 - ((clock.now - start) % 16); + } + + //eslint-disable-next-line jsdoc/require-jsdoc + function hrtime(prev) { + const millisSinceStart = clock.now - adjustedSystemTime[0] - start; + const secsSinceStart = Math.floor(millisSinceStart / 1000); + const remainderInNanos = + (millisSinceStart - secsSinceStart * 1e3) * 1e6 + + nanos - + adjustedSystemTime[1]; + + if (Array.isArray(prev)) { + if (prev[1] > 1e9) { + throw new TypeError( + "Number of nanoseconds can't exceed a billion" + ); + } + + const oldSecs = prev[0]; + let nanoDiff = remainderInNanos - prev[1]; + let secDiff = secsSinceStart - oldSecs; + + if (nanoDiff < 0) { + nanoDiff += 1e9; + secDiff -= 1; + } + + return [secDiff, nanoDiff]; + } + return [secsSinceStart, remainderInNanos]; + } + + if (hrtimeBigintPresent) { + hrtime.bigint = function () { + const parts = hrtime(); + return BigInt(parts[0]) * BigInt(1e9) + BigInt(parts[1]); // eslint-disable-line + }; + } + + clock.requestIdleCallback = function requestIdleCallback( + func, + timeout + ) { + let timeToNextIdlePeriod = 0; + + if (clock.countTimers() > 0) { + timeToNextIdlePeriod = 50; // const for now + } + + const result = addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 2), + delay: + typeof timeout === "undefined" + ? timeToNextIdlePeriod + : Math.min(timeout, timeToNextIdlePeriod), + idleCallback: true, + }); + + return Number(result); + }; + + clock.cancelIdleCallback = function cancelIdleCallback(timerId) { + return clearTimer(clock, timerId, "IdleCallback"); + }; + + clock.setTimeout = function setTimeout(func, timeout) { + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 2), + delay: timeout, + }); + }; + if (typeof _global.Promise !== "undefined" && utilPromisify) { + clock.setTimeout[ + utilPromisify.custom + ] = function promisifiedSetTimeout(timeout, arg) { + return new _global.Promise(function setTimeoutExecutor( + resolve + ) { + addTimer(clock, { + func: resolve, + args: [arg], + delay: timeout, + }); + }); + }; + } + + clock.clearTimeout = function clearTimeout(timerId) { + return clearTimer(clock, timerId, "Timeout"); + }; + + clock.nextTick = function nextTick(func) { + return enqueueJob(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 1), + error: isNearInfiniteLimit ? new Error() : null, + }); + }; + + clock.queueMicrotask = function queueMicrotask(func) { + return clock.nextTick(func); // explicitly drop additional arguments + }; + + clock.setInterval = function setInterval(func, timeout) { + // eslint-disable-next-line no-param-reassign + timeout = parseInt(timeout, 10); + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 2), + delay: timeout, + interval: timeout, + }); + }; + + clock.clearInterval = function clearInterval(timerId) { + return clearTimer(clock, timerId, "Interval"); + }; + + if (setImmediatePresent) { + clock.setImmediate = function setImmediate(func) { + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 1), + immediate: true, + }); + }; + + if (typeof _global.Promise !== "undefined" && utilPromisify) { + clock.setImmediate[ + utilPromisify.custom + ] = function promisifiedSetImmediate(arg) { + return new _global.Promise(function setImmediateExecutor( + resolve + ) { + addTimer(clock, { + func: resolve, + args: [arg], + immediate: true, + }); + }); + }; + } + + clock.clearImmediate = function clearImmediate(timerId) { + return clearTimer(clock, timerId, "Immediate"); + }; + } + + clock.countTimers = function countTimers() { + return ( + Object.keys(clock.timers || {}).length + + (clock.jobs || []).length + ); + }; + + clock.requestAnimationFrame = function requestAnimationFrame(func) { + const result = addTimer(clock, { + func: func, + delay: getTimeToNextFrame(), + args: [clock.now + getTimeToNextFrame()], + animation: true, + }); + + return Number(result); + }; + + clock.cancelAnimationFrame = function cancelAnimationFrame(timerId) { + return clearTimer(clock, timerId, "AnimationFrame"); + }; + + clock.runMicrotasks = function runMicrotasks() { + runJobs(clock); + }; + + /** + * @param {number|string} tickValue milliseconds or a string parseable by parseTime + * @param {boolean} isAsync + * @param {Function} resolve + * @param {Function} reject + * @returns {number|undefined} will return the new `now` value or nothing for async + */ + function doTick(tickValue, isAsync, resolve, reject) { + const msFloat = + typeof tickValue === "number" + ? tickValue + : parseTime(tickValue); + const ms = Math.floor(msFloat); + const remainder = nanoRemainder(msFloat); + let nanosTotal = nanos + remainder; + let tickTo = clock.now + ms; + + if (msFloat < 0) { + throw new TypeError("Negative ticks are not supported"); + } + + // adjust for positive overflow + if (nanosTotal >= 1e6) { + tickTo += 1; + nanosTotal -= 1e6; + } + + nanos = nanosTotal; + let tickFrom = clock.now; + let previous = clock.now; + // ESLint fails to detect this correctly + /* eslint-disable prefer-const */ + let timer, + firstException, + oldNow, + nextPromiseTick, + compensationCheck, + postTimerCall; + /* eslint-enable prefer-const */ + + clock.duringTick = true; + + // perform microtasks + oldNow = clock.now; + runJobs(clock); + if (oldNow !== clock.now) { + // compensate for any setSystemTime() call during microtask callback + tickFrom += clock.now - oldNow; + tickTo += clock.now - oldNow; + } + + //eslint-disable-next-line jsdoc/require-jsdoc + function doTickInner() { + // perform each timer in the requested range + timer = firstTimerInRange(clock, tickFrom, tickTo); + // eslint-disable-next-line no-unmodified-loop-condition + while (timer && tickFrom <= tickTo) { + if (clock.timers[timer.id]) { + tickFrom = timer.callAt; + clock.now = timer.callAt; + oldNow = clock.now; + try { + runJobs(clock); + callTimer(clock, timer); + } catch (e) { + firstException = firstException || e; + } + + if (isAsync) { + // finish up after native setImmediate callback to allow + // all native es6 promises to process their callbacks after + // each timer fires. + originalSetTimeout(nextPromiseTick); + return; + } + + compensationCheck(); + } + + postTimerCall(); + } + + // perform process.nextTick()s again + oldNow = clock.now; + runJobs(clock); + if (oldNow !== clock.now) { + // compensate for any setSystemTime() call during process.nextTick() callback + tickFrom += clock.now - oldNow; + tickTo += clock.now - oldNow; + } + clock.duringTick = false; + + // corner case: during runJobs new timers were scheduled which could be in the range [clock.now, tickTo] + timer = firstTimerInRange(clock, tickFrom, tickTo); + if (timer) { + try { + clock.tick(tickTo - clock.now); // do it all again - for the remainder of the requested range + } catch (e) { + firstException = firstException || e; + } + } else { + // no timers remaining in the requested range: move the clock all the way to the end + clock.now = tickTo; + + // update nanos + nanos = nanosTotal; + } + if (firstException) { + throw firstException; + } + + if (isAsync) { + resolve(clock.now); + } else { + return clock.now; + } + } + + nextPromiseTick = + isAsync && + function () { + try { + compensationCheck(); + postTimerCall(); + doTickInner(); + } catch (e) { + reject(e); + } + }; + + compensationCheck = function () { + // compensate for any setSystemTime() call during timer callback + if (oldNow !== clock.now) { + tickFrom += clock.now - oldNow; + tickTo += clock.now - oldNow; + previous += clock.now - oldNow; + } + }; + + postTimerCall = function () { + timer = firstTimerInRange(clock, previous, tickTo); + previous = tickFrom; + }; + + return doTickInner(); + } + + /** + * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15" + * @returns {number} will return the new `now` value + */ + clock.tick = function tick(tickValue) { + return doTick(tickValue, false); + }; + + if (typeof _global.Promise !== "undefined") { + /** + * @param {string|number} tickValue number of milliseconds or a human-readable value like "01:11:15" + * @returns {Promise} + */ + clock.tickAsync = function tickAsync(tickValue) { + return new _global.Promise(function (resolve, reject) { + originalSetTimeout(function () { + try { + doTick(tickValue, true, resolve, reject); + } catch (e) { + reject(e); + } + }); + }); + }; + } + + clock.next = function next() { + runJobs(clock); + const timer = firstTimer(clock); + if (!timer) { + return clock.now; + } + + clock.duringTick = true; + try { + clock.now = timer.callAt; + callTimer(clock, timer); + runJobs(clock); + return clock.now; + } finally { + clock.duringTick = false; + } + }; + + if (typeof _global.Promise !== "undefined") { + clock.nextAsync = function nextAsync() { + return new _global.Promise(function (resolve, reject) { + originalSetTimeout(function () { + try { + const timer = firstTimer(clock); + if (!timer) { + resolve(clock.now); + return; + } + + let err; + clock.duringTick = true; + clock.now = timer.callAt; + try { + callTimer(clock, timer); + } catch (e) { + err = e; + } + clock.duringTick = false; + + originalSetTimeout(function () { + if (err) { + reject(err); + } else { + resolve(clock.now); + } + }); + } catch (e) { + reject(e); + } + }); + }); + }; + } + + clock.runAll = function runAll() { + let numTimers, i; + runJobs(clock); + for (i = 0; i < clock.loopLimit; i++) { + if (!clock.timers) { + resetIsNearInfiniteLimit(); + return clock.now; + } + + numTimers = Object.keys(clock.timers).length; + if (numTimers === 0) { + resetIsNearInfiniteLimit(); + return clock.now; + } + + clock.next(); + checkIsNearInfiniteLimit(clock, i); + } + + const excessJob = firstTimer(clock); + throw getInfiniteLoopError(clock, excessJob); + }; + + clock.runToFrame = function runToFrame() { + return clock.tick(getTimeToNextFrame()); + }; + + if (typeof _global.Promise !== "undefined") { + clock.runAllAsync = function runAllAsync() { + return new _global.Promise(function (resolve, reject) { + let i = 0; + /** + * + */ + function doRun() { + originalSetTimeout(function () { + try { + let numTimers; + if (i < clock.loopLimit) { + if (!clock.timers) { + resetIsNearInfiniteLimit(); + resolve(clock.now); + return; + } + + numTimers = Object.keys(clock.timers) + .length; + if (numTimers === 0) { + resetIsNearInfiniteLimit(); + resolve(clock.now); + return; + } + + clock.next(); + + i++; + + doRun(); + checkIsNearInfiniteLimit(clock, i); + return; + } + + const excessJob = firstTimer(clock); + reject(getInfiniteLoopError(clock, excessJob)); + } catch (e) { + reject(e); + } + }); + } + doRun(); + }); + }; + } + + clock.runToLast = function runToLast() { + const timer = lastTimer(clock); + if (!timer) { + runJobs(clock); + return clock.now; + } + + return clock.tick(timer.callAt - clock.now); + }; + + if (typeof _global.Promise !== "undefined") { + clock.runToLastAsync = function runToLastAsync() { + return new _global.Promise(function (resolve, reject) { + originalSetTimeout(function () { + try { + const timer = lastTimer(clock); + if (!timer) { + resolve(clock.now); + } + + resolve(clock.tickAsync(timer.callAt)); + } catch (e) { + reject(e); + } + }); + }); + }; + } + + clock.reset = function reset() { + nanos = 0; + clock.timers = {}; + clock.jobs = []; + clock.now = start; + }; + + clock.setSystemTime = function setSystemTime(systemTime) { + // determine time difference + const newNow = getEpoch(systemTime); + const difference = newNow - clock.now; + let id, timer; + + adjustedSystemTime[0] = adjustedSystemTime[0] + difference; + adjustedSystemTime[1] = adjustedSystemTime[1] + nanos; + // update 'system clock' + clock.now = newNow; + nanos = 0; + + // update timers and intervals to keep them stable + for (id in clock.timers) { + if (clock.timers.hasOwnProperty(id)) { + timer = clock.timers[id]; + timer.createdAt += difference; + timer.callAt += difference; + } + } + }; + + if (performancePresent) { + clock.performance = Object.create(null); + clock.performance.now = function FakeTimersNow() { + const hrt = hrtime(); + const millis = hrt[0] * 1000 + hrt[1] / 1e6; + return millis; + }; + } + + if (hrtimePresent) { + clock.hrtime = hrtime; + } + + return clock; + } + + /* eslint-disable complexity */ + + /** + * @param {Config=} [config] Optional config + * @returns {Clock} + */ + function install(config) { + if ( + arguments.length > 1 || + config instanceof Date || + Array.isArray(config) || + typeof config === "number" + ) { + throw new TypeError( + `FakeTimers.install called with ${String( + config + )} install requires an object parameter` + ); + } + + if (_global.Date.isFake === true) { + // Timers are already faked; this is a problem. + // Make the user reset timers before continuing. + throw new TypeError( + "Can't install fake timers twice on the same global object." + ); + } + + // eslint-disable-next-line no-param-reassign + config = typeof config !== "undefined" ? config : {}; + config.shouldAdvanceTime = config.shouldAdvanceTime || false; + config.advanceTimeDelta = config.advanceTimeDelta || 20; + config.shouldClearNativeTimers = + config.shouldClearNativeTimers || false; + + if (config.target) { + throw new TypeError( + "config.target is no longer supported. Use `withGlobal(target)` instead." + ); + } + + let i, l; + const clock = createClock(config.now, config.loopLimit); + clock.shouldClearNativeTimers = config.shouldClearNativeTimers; + + clock.uninstall = function () { + return uninstall(clock, config); + }; + + clock.methods = config.toFake || []; + + if (clock.methods.length === 0) { + // do not fake nextTick by default - GitHub#126 + clock.methods = Object.keys(timers).filter(function (key) { + return key !== "nextTick" && key !== "queueMicrotask"; + }); + } + + if (config.shouldAdvanceTime === true) { + const intervalTick = doIntervalTick.bind( + null, + clock, + config.advanceTimeDelta + ); + const intervalId = _global.setInterval( + intervalTick, + config.advanceTimeDelta + ); + clock.attachedInterval = intervalId; + } + + if (clock.methods.includes("performance")) { + const proto = (() => { + if (hasPerformancePrototype) { + return _global.Performance.prototype; + } + if (hasPerformanceConstructorPrototype) { + return _global.performance.constructor.prototype; + } + })(); + if (proto) { + Object.getOwnPropertyNames(proto).forEach(function (name) { + if (name !== "now") { + clock.performance[name] = + name.indexOf("getEntries") === 0 + ? NOOP_ARRAY + : NOOP; + } + }); + } else if ((config.toFake || []).includes("performance")) { + // user explicitly tried to fake performance when not present + throw new ReferenceError( + "non-existent performance object cannot be faked" + ); + } + } + + for (i = 0, l = clock.methods.length; i < l; i++) { + const nameOfMethodToReplace = clock.methods[i]; + if (nameOfMethodToReplace === "hrtime") { + if ( + _global.process && + typeof _global.process.hrtime === "function" + ) { + hijackMethod(_global.process, nameOfMethodToReplace, clock); + } + } else if (nameOfMethodToReplace === "nextTick") { + if ( + _global.process && + typeof _global.process.nextTick === "function" + ) { + hijackMethod(_global.process, nameOfMethodToReplace, clock); + } + } else { + hijackMethod(_global, nameOfMethodToReplace, clock); + } + } + + return clock; + } + + /* eslint-enable complexity */ + + return { + timers: timers, + createClock: createClock, + install: install, + withGlobal: withGlobal, + }; +} + +/** + * @typedef {object} FakeTimers + * @property {Timers} timers + * @property {createClock} createClock + * @property {Function} install + * @property {withGlobal} withGlobal + */ + +/* eslint-enable complexity */ + +/** @type {FakeTimers} */ +const defaultImplementation = withGlobal(globalObject); + +exports.timers = defaultImplementation.timers; +exports.createClock = defaultImplementation.createClock; +exports.install = defaultImplementation.install; +exports.withGlobal = withGlobal; diff --git a/node_modules/@types/babel__core/LICENSE b/node_modules/@types/babel__core/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/babel__core/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/babel__core/README.md b/node_modules/@types/babel__core/README.md new file mode 100644 index 0000000..02ed4ad --- /dev/null +++ b/node_modules/@types/babel__core/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/babel__core` + +# Summary +This package contains type definitions for @babel/core (https://github.com/babel/babel/tree/master/packages/babel-core). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__core. + +### Additional Details + * Last updated: Sun, 20 Mar 2022 07:01:42 GMT + * Dependencies: [@types/babel__generator](https://npmjs.com/package/@types/babel__generator), [@types/babel__parser](https://npmjs.com/package/@types/babel__parser), [@types/babel__template](https://npmjs.com/package/@types/babel__template), [@types/babel__traverse](https://npmjs.com/package/@types/babel__traverse), [@types/babel__types](https://npmjs.com/package/@types/babel__types) + * Global values: `babel` + +# Credits +These definitions were written by [Troy Gerwien](https://github.com/yortus), [Marvin Hagemeister](https://github.com/marvinhagemeister), [Melvin Groenhoff](https://github.com/mgroenhoff), [Jessica Franco](https://github.com/Jessidhia), and [Ifiok Jr.](https://github.com/ifiokjr). diff --git a/node_modules/@types/babel__core/index.d.ts b/node_modules/@types/babel__core/index.d.ts new file mode 100644 index 0000000..c17be08 --- /dev/null +++ b/node_modules/@types/babel__core/index.d.ts @@ -0,0 +1,799 @@ +// Type definitions for @babel/core 7.1 +// Project: https://github.com/babel/babel/tree/master/packages/babel-core, https://babeljs.io +// Definitions by: Troy Gerwien +// Marvin Hagemeister +// Melvin Groenhoff +// Jessica Franco +// Ifiok Jr. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Minimum TypeScript Version: 3.4 + +import { GeneratorOptions } from '@babel/generator'; +import { ParserOptions } from '@babel/parser'; +import template from '@babel/template'; +import traverse, { Hub, NodePath, Scope, Visitor } from '@babel/traverse'; +import * as t from '@babel/types'; + +export { ParserOptions, GeneratorOptions, t as types, template, traverse, NodePath, Visitor }; + +export type Node = t.Node; +export type ParseResult = ReturnType; +export const version: string; +export const DEFAULT_EXTENSIONS: ['.js', '.jsx', '.es6', '.es', '.mjs']; + +/** + * Source map standard format as to revision 3 + * @see {@link https://sourcemaps.info/spec.html} + * @see {@link https://github.com/mozilla/source-map/blob/HEAD/source-map.d.ts} + */ +interface InputSourceMap { + version: number; + sources: string[]; + names: string[]; + sourceRoot?: string | undefined; + sourcesContent?: string[] | undefined; + mappings: string; + file: string; +} + +export interface TransformOptions { + /** + * Include the AST in the returned object + * + * Default: `false` + */ + ast?: boolean | null | undefined; + + /** + * Attach a comment after all non-user injected code + * + * Default: `null` + */ + auxiliaryCommentAfter?: string | null | undefined; + + /** + * Attach a comment before all non-user injected code + * + * Default: `null` + */ + auxiliaryCommentBefore?: string | null | undefined; + + /** + * Specify the "root" folder that defines the location to search for "babel.config.js", and the default folder to allow `.babelrc` files inside of. + * + * Default: `"."` + */ + root?: string | null | undefined; + + /** + * This option, combined with the "root" value, defines how Babel chooses its project root. + * The different modes define different ways that Babel can process the "root" value to get + * the final project root. + * + * @see https://babeljs.io/docs/en/next/options#rootmode + */ + rootMode?: 'root' | 'upward' | 'upward-optional' | undefined; + + /** + * The config file to load Babel's config from. Defaults to searching for "babel.config.js" inside the "root" folder. `false` will disable searching for config files. + * + * Default: `undefined` + */ + configFile?: string | boolean | null | undefined; + + /** + * Specify whether or not to use .babelrc and + * .babelignore files. + * + * Default: `true` + */ + babelrc?: boolean | null | undefined; + + /** + * Specify which packages should be search for .babelrc files when they are being compiled. `true` to always search, or a path string or an array of paths to packages to search + * inside of. Defaults to only searching the "root" package. + * + * Default: `(root)` + */ + babelrcRoots?: boolean | MatchPattern | MatchPattern[] | null | undefined; + + /** + * Toggles whether or not browserslist config sources are used, which includes searching for any browserslist files or referencing the browserslist key inside package.json. + * This is useful for projects that use a browserslist config for files that won't be compiled with Babel. + * + * If a string is specified, it must represent the path of a browserslist configuration file. Relative paths are resolved relative to the configuration file which specifies + * this option, or to `cwd` when it's passed as part of the programmatic options. + * + * Default: `true` + */ + browserslistConfigFile?: boolean | null | undefined; + + /** + * The Browserslist environment to use. + * + * Default: `undefined` + */ + browserslistEnv?: string | null | undefined; + + /** + * By default `babel.transformFromAst` will clone the input AST to avoid mutations. + * Specifying `cloneInputAst: false` can improve parsing performance if the input AST is not used elsewhere. + * + * Default: `true` + */ + cloneInputAst?: boolean | null | undefined; + + /** + * Defaults to environment variable `BABEL_ENV` if set, or else `NODE_ENV` if set, or else it defaults to `"development"` + * + * Default: env vars + */ + envName?: string | undefined; + + /** + * If any of patterns match, the current configuration object is considered inactive and is ignored during config processing. + */ + exclude?: MatchPattern | MatchPattern[] | undefined; + + /** + * Enable code generation + * + * Default: `true` + */ + code?: boolean | null | undefined; + + /** + * Output comments in generated output + * + * Default: `true` + */ + comments?: boolean | null | undefined; + + /** + * Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >500KB + * + * Default: `"auto"` + */ + compact?: boolean | 'auto' | null | undefined; + + /** + * The working directory that Babel's programmatic options are loaded relative to. + * + * Default: `"."` + */ + cwd?: string | null | undefined; + + /** + * Utilities may pass a caller object to identify themselves to Babel and + * pass capability-related flags for use by configs, presets and plugins. + * + * @see https://babeljs.io/docs/en/next/options#caller + */ + caller?: TransformCaller | undefined; + + /** + * This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { \/* specific options *\/ } } }` + * which will use those options when the `envName` is `production` + * + * Default: `{}` + */ + env?: { [index: string]: TransformOptions | null | undefined } | null | undefined; + + /** + * A path to a `.babelrc` file to extend + * + * Default: `null` + */ + extends?: string | null | undefined; + + /** + * Filename for use in errors etc + * + * Default: `"unknown"` + */ + filename?: string | null | undefined; + + /** + * Filename relative to `sourceRoot` + * + * Default: `(filename)` + */ + filenameRelative?: string | null | undefined; + + /** + * An object containing the options to be passed down to the babel code generator, @babel/generator + * + * Default: `{}` + */ + generatorOpts?: GeneratorOptions | null | undefined; + + /** + * Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used + * + * Default: `null` + */ + getModuleId?: ((moduleName: string) => string | null | undefined) | null | undefined; + + /** + * ANSI highlight syntax error code frames + * + * Default: `true` + */ + highlightCode?: boolean | null | undefined; + + /** + * Opposite to the `only` option. `ignore` is disregarded if `only` is specified + * + * Default: `null` + */ + ignore?: MatchPattern[] | null | undefined; + + /** + * This option is a synonym for "test" + */ + include?: MatchPattern | MatchPattern[] | undefined; + + /** + * A source map object that the output source map will be based on + * + * Default: `null` + */ + inputSourceMap?: InputSourceMap | null | undefined; + + /** + * Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe) + * + * Default: `false` + */ + minified?: boolean | null | undefined; + + /** + * Specify a custom name for module ids + * + * Default: `null` + */ + moduleId?: string | null | undefined; + + /** + * If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules) + * + * Default: `false` + */ + moduleIds?: boolean | null | undefined; + + /** + * Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions + * + * Default: `(sourceRoot)` + */ + moduleRoot?: string | null | undefined; + + /** + * A glob, regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile + * a non-matching file it's returned verbatim + * + * Default: `null` + */ + only?: MatchPattern[] | null | undefined; + + /** + * Allows users to provide an array of options that will be merged into the current configuration one at a time. + * This feature is best used alongside the "test"/"include"/"exclude" options to provide conditions for which an override should apply + */ + overrides?: TransformOptions[] | undefined; + + /** + * An object containing the options to be passed down to the babel parser, @babel/parser + * + * Default: `{}` + */ + parserOpts?: ParserOptions | null | undefined; + + /** + * List of plugins to load and use + * + * Default: `[]` + */ + plugins?: PluginItem[] | null | undefined; + + /** + * List of presets (a set of plugins) to load and use + * + * Default: `[]` + */ + presets?: PluginItem[] | null | undefined; + + /** + * Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE**: This will not retain the columns) + * + * Default: `false` + */ + retainLines?: boolean | null | undefined; + + /** + * An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE**: This overrides the `comment` option when used + * + * Default: `null` + */ + shouldPrintComment?: ((commentContents: string) => boolean) | null | undefined; + + /** + * Set `sources[0]` on returned source map + * + * Default: `(filenameRelative)` + */ + sourceFileName?: string | null | undefined; + + /** + * If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. If set to `"both"` + * then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!** + * + * Default: `false` + */ + sourceMaps?: boolean | 'inline' | 'both' | null | undefined; + + /** + * The root from which all sources are relative + * + * Default: `(moduleRoot)` + */ + sourceRoot?: string | null | undefined; + + /** + * Indicate the mode the code should be parsed in. Can be one of "script", "module", or "unambiguous". `"unambiguous"` will make Babel attempt to guess, based on the presence of ES6 + * `import` or `export` statements. Files with ES6 `import`s and `export`s are considered `"module"` and are otherwise `"script"`. + * + * Default: `("module")` + */ + sourceType?: 'script' | 'module' | 'unambiguous' | null | undefined; + + /** + * If all patterns fail to match, the current configuration object is considered inactive and is ignored during config processing. + */ + test?: MatchPattern | MatchPattern[] | undefined; + + /** + * An optional callback that can be used to wrap visitor methods. **NOTE**: This is useful for things like introspection, and not really needed for implementing anything. Called as + * `wrapPluginVisitorMethod(pluginAlias, visitorType, callback)`. + */ + wrapPluginVisitorMethod?: + | (( + pluginAlias: string, + visitorType: 'enter' | 'exit', + callback: (path: NodePath, state: any) => void, + ) => (path: NodePath, state: any) => void) + | null | undefined; +} + +export interface TransformCaller { + // the only required property + name: string; + // e.g. set to true by `babel-loader` and false by `babel-jest` + supportsStaticESM?: boolean | undefined; + supportsDynamicImport?: boolean | undefined; + supportsExportNamespaceFrom?: boolean | undefined; + supportsTopLevelAwait?: boolean | undefined; + // augment this with a "declare module '@babel/core' { ... }" if you need more keys +} + +export type FileResultCallback = (err: Error | null, result: BabelFileResult | null) => any; + +export interface MatchPatternContext { + envName: string; + dirname: string; + caller: TransformCaller | undefined; +} +export type MatchPattern = string | RegExp | ((filename: string | undefined, context: MatchPatternContext) => boolean); + +/** + * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST. + */ +export function transform(code: string, callback: FileResultCallback): void; + +/** + * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST. + */ +export function transform(code: string, opts: TransformOptions | undefined, callback: FileResultCallback): void; + +/** + * Here for backward-compatibility. Ideally use `transformSync` if you want a synchronous API. + */ +export function transform(code: string, opts?: TransformOptions): BabelFileResult | null; + +/** + * Transforms the passed in code. Returning an object with the generated code, source map, and AST. + */ +export function transformSync(code: string, opts?: TransformOptions): BabelFileResult | null; + +/** + * Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST. + */ +export function transformAsync(code: string, opts?: TransformOptions): Promise; + +/** + * Asynchronously transforms the entire contents of a file. + */ +export function transformFile(filename: string, callback: FileResultCallback): void; + +/** + * Asynchronously transforms the entire contents of a file. + */ +export function transformFile(filename: string, opts: TransformOptions | undefined, callback: FileResultCallback): void; + +/** + * Synchronous version of `babel.transformFile`. Returns the transformed contents of the `filename`. + */ +export function transformFileSync(filename: string, opts?: TransformOptions): BabelFileResult | null; + +/** + * Asynchronously transforms the entire contents of a file. + */ +export function transformFileAsync(filename: string, opts?: TransformOptions): Promise; + +/** + * Given an AST, transform it. + */ +export function transformFromAst(ast: Node, code: string | undefined, callback: FileResultCallback): void; + +/** + * Given an AST, transform it. + */ +export function transformFromAst( + ast: Node, + code: string | undefined, + opts: TransformOptions | undefined, + callback: FileResultCallback, +): void; + +/** + * Here for backward-compatibility. Ideally use ".transformSync" if you want a synchronous API. + */ +export function transformFromAstSync(ast: Node, code?: string, opts?: TransformOptions): BabelFileResult | null; + +/** + * Given an AST, transform it. + */ +export function transformFromAstAsync( + ast: Node, + code?: string, + opts?: TransformOptions, +): Promise; + +// A babel plugin is a simple function which must return an object matching +// the following interface. Babel will throw if it finds unknown properties. +// The list of allowed plugin keys is here: +// https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-core/src/config/option-manager.js#L71 +export interface PluginObj { + name?: string | undefined; + manipulateOptions?(opts: any, parserOpts: any): void; + pre?(this: S, file: BabelFile): void; + visitor: Visitor; + post?(this: S, file: BabelFile): void; + inherits?: any; +} + +export interface BabelFile { + ast: t.File; + opts: TransformOptions; + hub: Hub; + metadata: object; + path: NodePath; + scope: Scope; + inputMap: object | null; + code: string; +} + +export interface PluginPass { + file: BabelFile; + key: string; + opts: object; + cwd: string; + filename: string | undefined; + get(key: unknown): any; + set(key: unknown, value: unknown): void; + [key: string]: unknown; +} + +export interface BabelFileResult { + ast?: t.File | null | undefined; + code?: string | null | undefined; + ignored?: boolean | undefined; + map?: { + version: number; + sources: string[]; + names: string[]; + sourceRoot?: string | undefined; + sourcesContent?: string[] | undefined; + mappings: string; + file: string; + } | null | undefined; + metadata?: BabelFileMetadata | undefined; +} + +export interface BabelFileMetadata { + usedHelpers: string[]; + marked: Array<{ + type: string; + message: string; + loc: object; + }>; + modules: BabelFileModulesMetadata; +} + +export interface BabelFileModulesMetadata { + imports: object[]; + exports: { + exported: object[]; + specifiers: object[]; + }; +} + +export type FileParseCallback = (err: Error | null, result: ParseResult | null) => any; + +/** + * Given some code, parse it using Babel's standard behavior. + * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled. + */ +export function parse(code: string, callback: FileParseCallback): void; + +/** + * Given some code, parse it using Babel's standard behavior. + * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled. + */ +export function parse(code: string, options: TransformOptions | undefined, callback: FileParseCallback): void; + +/** + * Given some code, parse it using Babel's standard behavior. + * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled. + */ +export function parse(code: string, options?: TransformOptions): ParseResult | null; + +/** + * Given some code, parse it using Babel's standard behavior. + * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled. + */ +export function parseSync(code: string, options?: TransformOptions): ParseResult | null; + +/** + * Given some code, parse it using Babel's standard behavior. + * Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled. + */ +export function parseAsync(code: string, options?: TransformOptions): Promise; + +/** + * Resolve Babel's options fully, resulting in an options object where: + * + * * opts.plugins is a full list of Plugin instances. + * * opts.presets is empty and all presets are flattened into opts. + * * It can be safely passed back to Babel. Fields like babelrc have been set to false so that later calls to Babel + * will not make a second attempt to load config files. + * + * Plugin instances aren't meant to be manipulated directly, but often callers will serialize this opts to JSON to + * use it as a cache key representing the options Babel has received. Caching on this isn't 100% guaranteed to + * invalidate properly, but it is the best we have at the moment. + */ +export function loadOptions(options?: TransformOptions): object | null; + +/** + * To allow systems to easily manipulate and validate a user's config, this function resolves the plugins and + * presets and proceeds no further. The expectation is that callers will take the config's .options, manipulate it + * as then see fit and pass it back to Babel again. + * + * * `babelrc: string | void` - The path of the `.babelrc` file, if there was one. + * * `babelignore: string | void` - The path of the `.babelignore` file, if there was one. + * * `options: ValidatedOptions` - The partially resolved options, which can be manipulated and passed back + * to Babel again. + * * `plugins: Array` - See below. + * * `presets: Array` - See below. + * * It can be safely passed back to Babel. Fields like `babelrc` have been set to false so that later calls to + * Babel will not make a second attempt to load config files. + * + * `ConfigItem` instances expose properties to introspect the values, but each item should be treated as + * immutable. If changes are desired, the item should be removed from the list and replaced with either a normal + * Babel config value, or with a replacement item created by `babel.createConfigItem`. See that function for + * information about `ConfigItem` fields. + */ +export function loadPartialConfig(options?: TransformOptions): Readonly | null; +export function loadPartialConfigAsync(options?: TransformOptions): Promise | null>; + +export interface PartialConfig { + options: TransformOptions; + babelrc?: string | undefined; + babelignore?: string | undefined; + config?: string | undefined; + hasFilesystemConfig: () => boolean; +} + +export interface ConfigItem { + /** + * The name that the user gave the plugin instance, e.g. `plugins: [ ['env', {}, 'my-env'] ]` + */ + name?: string | undefined; + + /** + * The resolved value of the plugin. + */ + value: object | ((...args: any[]) => any); + + /** + * The options object passed to the plugin. + */ + options?: object | false | undefined; + + /** + * The path that the options are relative to. + */ + dirname: string; + + /** + * Information about the plugin's file, if Babel knows it. + * * + */ + file?: { + /** + * The file that the user requested, e.g. `"@babel/env"` + */ + request: string; + + /** + * The full path of the resolved file, e.g. `"/tmp/node_modules/@babel/preset-env/lib/index.js"` + */ + resolved: string; + } | null | undefined; +} + +export type PluginOptions = object | undefined | false; + +export type PluginTarget = string | object | ((...args: any[]) => any); + +export type PluginItem = + | ConfigItem + | PluginObj + | PluginTarget + | [PluginTarget, PluginOptions] + | [PluginTarget, PluginOptions, string | undefined]; + +export function resolvePlugin(name: string, dirname: string): string | null; +export function resolvePreset(name: string, dirname: string): string | null; + +export interface CreateConfigItemOptions { + dirname?: string | undefined; + type?: 'preset' | 'plugin' | undefined; +} + +/** + * Allows build tooling to create and cache config items up front. If this function is called multiple times for a + * given plugin, Babel will call the plugin's function itself multiple times. If you have a clear set of expected + * plugins and presets to inject, pre-constructing the config items would be recommended. + */ +export function createConfigItem( + value: PluginTarget | [PluginTarget, PluginOptions] | [PluginTarget, PluginOptions, string | undefined], + options?: CreateConfigItemOptions, +): ConfigItem; + +// NOTE: the documentation says the ConfigAPI also exposes @babel/core's exports, but it actually doesn't +/** + * @see https://babeljs.io/docs/en/next/config-files#config-function-api + */ +export interface ConfigAPI { + /** + * The version string for the Babel version that is loading the config file. + * + * @see https://babeljs.io/docs/en/next/config-files#apiversion + */ + version: string; + /** + * @see https://babeljs.io/docs/en/next/config-files#apicache + */ + cache: SimpleCacheConfigurator; + /** + * @see https://babeljs.io/docs/en/next/config-files#apienv + */ + env: EnvFunction; + // undocumented; currently hardcoded to return 'false' + // async(): boolean + /** + * This API is used as a way to access the `caller` data that has been passed to Babel. + * Since many instances of Babel may be running in the same process with different `caller` values, + * this API is designed to automatically configure `api.cache`, the same way `api.env()` does. + * + * The `caller` value is available as the first parameter of the callback function. + * It is best used with something like this to toggle configuration behavior + * based on a specific environment: + * + * @example + * function isBabelRegister(caller?: { name: string }) { + * return !!(caller && caller.name === "@babel/register") + * } + * api.caller(isBabelRegister) + * + * @see https://babeljs.io/docs/en/next/config-files#apicallercb + */ + caller(callerCallback: (caller: TransformOptions['caller']) => T): T; + /** + * While `api.version` can be useful in general, it's sometimes nice to just declare your version. + * This API exposes a simple way to do that with: + * + * @example + * api.assertVersion(7) // major version only + * api.assertVersion("^7.2") + * + * @see https://babeljs.io/docs/en/next/config-files#apiassertversionrange + */ + assertVersion(versionRange: number | string): boolean; + // NOTE: this is an undocumented reexport from "@babel/parser" but it's missing from its types + // tokTypes: typeof tokTypes +} + +/** + * JS configs are great because they can compute a config on the fly, + * but the downside there is that it makes caching harder. + * Babel wants to avoid re-executing the config function every time a file is compiled, + * because then it would also need to re-execute any plugin and preset functions + * referenced in that config. + * + * To avoid this, Babel expects users of config functions to tell it how to manage caching + * within a config file. + * + * @see https://babeljs.io/docs/en/next/config-files#apicache + */ +export interface SimpleCacheConfigurator { + // there is an undocumented call signature that is a shorthand for forever()/never()/using(). + // (ever: boolean): void + // (callback: CacheCallback): T + /** + * Permacache the computed config and never call the function again. + */ + forever(): void; + /** + * Do not cache this config, and re-execute the function every time. + */ + never(): void; + /** + * Any time the using callback returns a value other than the one that was expected, + * the overall config function will be called again and a new entry will be added to the cache. + * + * @example + * api.cache.using(() => process.env.NODE_ENV) + */ + using(callback: SimpleCacheCallback): T; + /** + * Any time the using callback returns a value other than the one that was expected, + * the overall config function will be called again and all entries in the cache will + * be replaced with the result. + * + * @example + * api.cache.invalidate(() => process.env.NODE_ENV) + */ + invalidate(callback: SimpleCacheCallback): T; +} + +// https://github.com/babel/babel/blob/v7.3.3/packages/babel-core/src/config/caching.js#L231 +export type SimpleCacheKey = string | boolean | number | null | undefined; +export type SimpleCacheCallback = () => T; + +/** + * Since `NODE_ENV` is a fairly common way to toggle behavior, Babel also includes an API function + * meant specifically for that. This API is used as a quick way to check the `"envName"` that Babel + * was loaded with, which takes `NODE_ENV` into account if no other overriding environment is set. + * + * @see https://babeljs.io/docs/en/next/config-files#apienv + */ +export interface EnvFunction { + /** + * @returns the current `envName` string + */ + (): string; + /** + * @returns `true` if the `envName` is `===` any of the given strings + */ + (envName: string | ReadonlyArray): boolean; + // the official documentation is misleading for this one... + // this just passes the callback to `cache.using` but with an additional argument. + // it returns its result instead of necessarily returning a boolean. + (envCallback: (envName: NonNullable) => T): T; +} + +export type ConfigFunction = (api: ConfigAPI) => TransformOptions; + +export as namespace babel; diff --git a/node_modules/@types/babel__core/package.json b/node_modules/@types/babel__core/package.json new file mode 100644 index 0000000..1d2d92e --- /dev/null +++ b/node_modules/@types/babel__core/package.json @@ -0,0 +1,51 @@ +{ + "name": "@types/babel__core", + "version": "7.1.19", + "description": "TypeScript definitions for @babel/core", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__core", + "license": "MIT", + "contributors": [ + { + "name": "Troy Gerwien", + "url": "https://github.com/yortus", + "githubUsername": "yortus" + }, + { + "name": "Marvin Hagemeister", + "url": "https://github.com/marvinhagemeister", + "githubUsername": "marvinhagemeister" + }, + { + "name": "Melvin Groenhoff", + "url": "https://github.com/mgroenhoff", + "githubUsername": "mgroenhoff" + }, + { + "name": "Jessica Franco", + "url": "https://github.com/Jessidhia", + "githubUsername": "Jessidhia" + }, + { + "name": "Ifiok Jr.", + "url": "https://github.com/ifiokjr", + "githubUsername": "ifiokjr" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/babel__core" + }, + "scripts": {}, + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + }, + "typesPublisherContentHash": "5358ce595fd2768093c1ef80a9b4e731532c9c96f303bea08913d5e19a166a90", + "typeScriptVersion": "3.9" +} \ No newline at end of file diff --git a/node_modules/@types/babel__generator/LICENSE b/node_modules/@types/babel__generator/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/babel__generator/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/babel__generator/README.md b/node_modules/@types/babel__generator/README.md new file mode 100644 index 0000000..a9c68c9 --- /dev/null +++ b/node_modules/@types/babel__generator/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/babel__generator` + +# Summary +This package contains type definitions for @babel/generator (https://github.com/babel/babel/tree/master/packages/babel-generator). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__generator. + +### Additional Details + * Last updated: Thu, 23 Dec 2021 23:34:17 GMT + * Dependencies: [@types/babel__types](https://npmjs.com/package/@types/babel__types) + * Global values: none + +# Credits +These definitions were written by [Troy Gerwien](https://github.com/yortus), [Melvin Groenhoff](https://github.com/mgroenhoff), [Cameron Yan](https://github.com/khell), and [Lyanbin](https://github.com/Lyanbin). diff --git a/node_modules/@types/babel__generator/index.d.ts b/node_modules/@types/babel__generator/index.d.ts new file mode 100644 index 0000000..61317bf --- /dev/null +++ b/node_modules/@types/babel__generator/index.d.ts @@ -0,0 +1,211 @@ +// Type definitions for @babel/generator 7.6 +// Project: https://github.com/babel/babel/tree/master/packages/babel-generator, https://babeljs.io +// Definitions by: Troy Gerwien +// Melvin Groenhoff +// Cameron Yan +// Lyanbin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import * as t from '@babel/types'; + +export interface GeneratorOptions { + /** + * Optional string to add as a block comment at the start of the output file. + */ + auxiliaryCommentBefore?: string | undefined; + + /** + * Optional string to add as a block comment at the end of the output file. + */ + auxiliaryCommentAfter?: string | undefined; + + /** + * Function that takes a comment (as a string) and returns true if the comment should be included in the output. + * By default, comments are included if `opts.comments` is `true` or if `opts.minifed` is `false` and the comment + * contains `@preserve` or `@license`. + */ + shouldPrintComment?(comment: string): boolean; + + /** + * Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces). + * Defaults to `false`. + */ + retainLines?: boolean | undefined; + + /** + * Retain parens around function expressions (could be used to change engine parsing behavior) + * Defaults to `false`. + */ + retainFunctionParens?: boolean | undefined; + + /** + * Should comments be included in output? Defaults to `true`. + */ + comments?: boolean | undefined; + + /** + * Set to true to avoid adding whitespace for formatting. Defaults to the value of `opts.minified`. + */ + compact?: boolean | 'auto' | undefined; + + /** + * Should the output be minified. Defaults to `false`. + */ + minified?: boolean | undefined; + + /** + * Set to true to reduce whitespace (but not as much as opts.compact). Defaults to `false`. + */ + concise?: boolean | undefined; + + /** + * Used in warning messages + */ + filename?: string | undefined; + + /** + * Enable generating source maps. Defaults to `false`. + */ + sourceMaps?: boolean | undefined; + + /** + * A root for all relative URLs in the source map. + */ + sourceRoot?: string | undefined; + + /** + * The filename for the source code (i.e. the code in the `code` argument). + * This will only be used if `code` is a string. + */ + sourceFileName?: string | undefined; + + /** + * Set to true to run jsesc with "json": true to print "\u00A9" vs. "©"; + */ + jsonCompatibleStrings?: boolean | undefined; + + /** + * Set to true to enable support for experimental decorators syntax before module exports. + * Defaults to `false`. + */ + decoratorsBeforeExport?: boolean | undefined; + + /** + * Options for outputting jsesc representation. + */ + jsescOption?: { + /** + * The default value for the quotes option is 'single'. This means that any occurrences of ' in the input + * string are escaped as \', so that the output can be used in a string literal wrapped in single quotes. + */ + quotes?: 'single' | 'double' | 'backtick' | undefined; + + /** + * The default value for the numbers option is 'decimal'. This means that any numeric values are represented + * using decimal integer literals. Other valid options are binary, octal, and hexadecimal, which result in + * binary integer literals, octal integer literals, and hexadecimal integer literals, respectively. + */ + numbers?: 'binary' | 'octal' | 'decimal' | 'hexadecimal' | undefined; + + /** + * The wrap option takes a boolean value (true or false), and defaults to false (disabled). When enabled, the + * output is a valid JavaScript string literal wrapped in quotes. The type of quotes can be specified through + * the quotes setting. + */ + wrap?: boolean | undefined; + + /** + * The es6 option takes a boolean value (true or false), and defaults to false (disabled). When enabled, any + * astral Unicode symbols in the input are escaped using ECMAScript 6 Unicode code point escape sequences + * instead of using separate escape sequences for each surrogate half. If backwards compatibility with ES5 + * environments is a concern, don’t enable this setting. If the json setting is enabled, the value for the es6 + * setting is ignored (as if it was false). + */ + es6?: boolean | undefined; + + /** + * The escapeEverything option takes a boolean value (true or false), and defaults to false (disabled). When + * enabled, all the symbols in the output are escaped — even printable ASCII symbols. + */ + escapeEverything?: boolean | undefined; + + /** + * The minimal option takes a boolean value (true or false), and defaults to false (disabled). When enabled, + * only a limited set of symbols in the output are escaped: \0, \b, \t, \n, \f, \r, \\, \u2028, \u2029. + */ + minimal?: boolean | undefined; + + /** + * The isScriptContext option takes a boolean value (true or false), and defaults to false (disabled). When + * enabled, occurrences of or + + `; +} + +function headerTemplate(details) { + function metricsTemplate({ pct, covered, total }, kind) { + return ` +
+ ${pct}% + ${kind} + ${covered}/${total} +
+ `; + } + + function skipTemplate(metrics) { + const statements = metrics.statements.skipped; + const branches = metrics.branches.skipped; + const functions = metrics.functions.skipped; + + const countLabel = (c, label, plural) => + c === 0 ? [] : `${c} ${label}${c === 1 ? '' : plural}`; + const skips = [].concat( + countLabel(statements, 'statement', 's'), + countLabel(functions, 'function', 's'), + countLabel(branches, 'branch', 'es') + ); + + if (skips.length === 0) { + return ''; + } + + return ` +
+ ${skips.join(', ')} + Ignored      +
+ `; + } + + return ` + + +${htmlHead(details)} + +
+
+

${details.pathHtml}

+
+ ${metricsTemplate(details.metrics.statements, 'Statements')} + ${metricsTemplate(details.metrics.branches, 'Branches')} + ${metricsTemplate(details.metrics.functions, 'Functions')} + ${metricsTemplate(details.metrics.lines, 'Lines')} + ${skipTemplate(details.metrics)} +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+ +
+
+ `; +} + +function footerTemplate(details) { + return ` +
+
+ + + + + + + + `; +} + +function detailTemplate(data) { + const lineNumbers = new Array(data.maxLines).fill().map((_, i) => i + 1); + const lineLink = num => + `${num}`; + const lineCount = line => + `${line.hits}`; + + /* This is rendered in a `
`, need control of all whitespace. */
+    return [
+        '',
+        `${lineNumbers
+            .map(lineLink)
+            .join('\n')}`,
+        `${data.lineCoverage
+            .map(lineCount)
+            .join('\n')}`,
+        `
${data.annotatedCode.join(
+            '\n'
+        )}
`, + '' + ].join(''); +} +const summaryTableHeader = [ + '
', + '', + '', + '', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + '', + '', + '' +].join('\n'); + +function summaryLineTemplate(details) { + const { reportClasses, metrics, file, output } = details; + const percentGraph = pct => { + if (!isFinite(pct)) { + return ''; + } + + const cls = ['cover-fill']; + if (pct === 100) { + cls.push('cover-full'); + } + + pct = Math.floor(pct); + return [ + `
`, + `
` + ].join(''); + }; + const summaryType = (type, showGraph = false) => { + const info = metrics[type]; + const reportClass = reportClasses[type]; + const result = [ + ``, + `` + ]; + if (showGraph) { + result.unshift( + `` + ); + } + + return result; + }; + + return [] + .concat( + '', + ``, + summaryType('statements', true), + summaryType('branches'), + summaryType('functions'), + summaryType('lines'), + '\n' + ) + .join('\n\t'); +} + +const summaryTableFooter = ['', '
FileStatementsBranchesFunctionsLines
${info.pct}%${info.covered}/${info.total}`, + `
${percentGraph(info.pct)}
`, + `
${html.escape(file)}
', '
'].join('\n'); +const emptyClasses = { + statements: 'empty', + lines: 'empty', + functions: 'empty', + branches: 'empty' +}; + +const standardLinkMapper = { + getPath(node) { + if (typeof node === 'string') { + return node; + } + let filePath = node.getQualifiedName(); + if (node.isSummary()) { + if (filePath !== '') { + filePath += '/index.html'; + } else { + filePath = 'index.html'; + } + } else { + filePath += '.html'; + } + return filePath; + }, + + relativePath(source, target) { + const targetPath = this.getPath(target); + const sourcePath = path.dirname(this.getPath(source)); + return path.posix.relative(sourcePath, targetPath); + }, + + assetPath(node, name) { + return this.relativePath(this.getPath(node), name); + } +}; + +function fixPct(metrics) { + Object.keys(emptyClasses).forEach(key => { + metrics[key].pct = 0; + }); + return metrics; +} + +class HtmlReport extends ReportBase { + constructor(opts) { + super(); + + this.verbose = opts.verbose; + this.linkMapper = opts.linkMapper || standardLinkMapper; + this.subdir = opts.subdir || ''; + this.date = new Date().toISOString(); + this.skipEmpty = opts.skipEmpty; + } + + getBreadcrumbHtml(node) { + let parent = node.getParent(); + const nodePath = []; + + while (parent) { + nodePath.push(parent); + parent = parent.getParent(); + } + + const linkPath = nodePath.map(ancestor => { + const target = this.linkMapper.relativePath(node, ancestor); + const name = ancestor.getRelativeName() || 'All files'; + return '' + name + ''; + }); + + linkPath.reverse(); + return linkPath.length > 0 + ? linkPath.join(' / ') + ' ' + node.getRelativeName() + : 'All files'; + } + + fillTemplate(node, templateData, context) { + const linkMapper = this.linkMapper; + const summary = node.getCoverageSummary(); + templateData.entity = node.getQualifiedName() || 'All files'; + templateData.metrics = summary; + templateData.reportClass = context.classForPercent( + 'statements', + summary.statements.pct + ); + templateData.pathHtml = this.getBreadcrumbHtml(node); + templateData.base = { + css: linkMapper.assetPath(node, 'base.css') + }; + templateData.sorter = { + js: linkMapper.assetPath(node, 'sorter.js'), + image: linkMapper.assetPath(node, 'sort-arrow-sprite.png') + }; + templateData.blockNavigation = { + js: linkMapper.assetPath(node, 'block-navigation.js') + }; + templateData.prettify = { + js: linkMapper.assetPath(node, 'prettify.js'), + css: linkMapper.assetPath(node, 'prettify.css') + }; + templateData.favicon = linkMapper.assetPath(node, 'favicon.png'); + } + + getTemplateData() { + return { datetime: this.date }; + } + + getWriter(context) { + if (!this.subdir) { + return context.writer; + } + return context.writer.writerForDir(this.subdir); + } + + onStart(root, context) { + const assetHeaders = { + '.js': '/* eslint-disable */\n' + }; + + ['.', 'vendor'].forEach(subdir => { + const writer = this.getWriter(context); + const srcDir = path.resolve(__dirname, 'assets', subdir); + fs.readdirSync(srcDir).forEach(f => { + const resolvedSource = path.resolve(srcDir, f); + const resolvedDestination = '.'; + const stat = fs.statSync(resolvedSource); + let dest; + + if (stat.isFile()) { + dest = resolvedDestination + '/' + f; + if (this.verbose) { + console.log('Write asset: ' + dest); + } + writer.copyFile( + resolvedSource, + dest, + assetHeaders[path.extname(f)] + ); + } + }); + }); + } + + onSummary(node, context) { + const linkMapper = this.linkMapper; + const templateData = this.getTemplateData(); + const children = node.getChildren(); + const skipEmpty = this.skipEmpty; + + this.fillTemplate(node, templateData, context); + const cw = this.getWriter(context).writeFile(linkMapper.getPath(node)); + cw.write(headerTemplate(templateData)); + cw.write(summaryTableHeader); + children.forEach(child => { + const metrics = child.getCoverageSummary(); + const isEmpty = metrics.isEmpty(); + if (skipEmpty && isEmpty) { + return; + } + const reportClasses = isEmpty + ? emptyClasses + : { + statements: context.classForPercent( + 'statements', + metrics.statements.pct + ), + lines: context.classForPercent( + 'lines', + metrics.lines.pct + ), + functions: context.classForPercent( + 'functions', + metrics.functions.pct + ), + branches: context.classForPercent( + 'branches', + metrics.branches.pct + ) + }; + const data = { + metrics: isEmpty ? fixPct(metrics) : metrics, + reportClasses, + file: child.getRelativeName(), + output: linkMapper.relativePath(node, child) + }; + cw.write(summaryLineTemplate(data) + '\n'); + }); + cw.write(summaryTableFooter); + cw.write(footerTemplate(templateData)); + cw.close(); + } + + onDetail(node, context) { + const linkMapper = this.linkMapper; + const templateData = this.getTemplateData(); + + this.fillTemplate(node, templateData, context); + const cw = this.getWriter(context).writeFile(linkMapper.getPath(node)); + cw.write(headerTemplate(templateData)); + cw.write('
\n');
+        cw.write(detailTemplate(annotator(node.getFileCoverage(), context)));
+        cw.write('
\n'); + cw.write(footerTemplate(templateData)); + cw.close(); + } +} + +module.exports = HtmlReport; diff --git a/node_modules/istanbul-reports/lib/html/insertion-text.js b/node_modules/istanbul-reports/lib/html/insertion-text.js new file mode 100644 index 0000000..6f80642 --- /dev/null +++ b/node_modules/istanbul-reports/lib/html/insertion-text.js @@ -0,0 +1,114 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +function InsertionText(text, consumeBlanks) { + this.text = text; + this.origLength = text.length; + this.offsets = []; + this.consumeBlanks = consumeBlanks; + this.startPos = this.findFirstNonBlank(); + this.endPos = this.findLastNonBlank(); +} + +const WHITE_RE = /[ \f\n\r\t\v\u00A0\u2028\u2029]/; + +InsertionText.prototype = { + findFirstNonBlank() { + let pos = -1; + const text = this.text; + const len = text.length; + let i; + for (i = 0; i < len; i += 1) { + if (!text.charAt(i).match(WHITE_RE)) { + pos = i; + break; + } + } + return pos; + }, + findLastNonBlank() { + const text = this.text; + const len = text.length; + let pos = text.length + 1; + let i; + for (i = len - 1; i >= 0; i -= 1) { + if (!text.charAt(i).match(WHITE_RE)) { + pos = i; + break; + } + } + return pos; + }, + originalLength() { + return this.origLength; + }, + + insertAt(col, str, insertBefore, consumeBlanks) { + consumeBlanks = + typeof consumeBlanks === 'undefined' + ? this.consumeBlanks + : consumeBlanks; + col = col > this.originalLength() ? this.originalLength() : col; + col = col < 0 ? 0 : col; + + if (consumeBlanks) { + if (col <= this.startPos) { + col = 0; + } + if (col > this.endPos) { + col = this.origLength; + } + } + + const len = str.length; + const offset = this.findOffset(col, len, insertBefore); + const realPos = col + offset; + const text = this.text; + this.text = text.substring(0, realPos) + str + text.substring(realPos); + return this; + }, + + findOffset(pos, len, insertBefore) { + const offsets = this.offsets; + let offsetObj; + let cumulativeOffset = 0; + let i; + + for (i = 0; i < offsets.length; i += 1) { + offsetObj = offsets[i]; + if ( + offsetObj.pos < pos || + (offsetObj.pos === pos && !insertBefore) + ) { + cumulativeOffset += offsetObj.len; + } + if (offsetObj.pos >= pos) { + break; + } + } + if (offsetObj && offsetObj.pos === pos) { + offsetObj.len += len; + } else { + offsets.splice(i, 0, { pos, len }); + } + return cumulativeOffset; + }, + + wrap(startPos, startText, endPos, endText, consumeBlanks) { + this.insertAt(startPos, startText, true, consumeBlanks); + this.insertAt(endPos, endText, false, consumeBlanks); + return this; + }, + + wrapLine(startText, endText) { + this.wrap(0, startText, this.originalLength(), endText); + }, + + toString() { + return this.text; + } +}; + +module.exports = InsertionText; diff --git a/node_modules/istanbul-reports/lib/json-summary/index.js b/node_modules/istanbul-reports/lib/json-summary/index.js new file mode 100644 index 0000000..318a47f --- /dev/null +++ b/node_modules/istanbul-reports/lib/json-summary/index.js @@ -0,0 +1,56 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +class JsonSummaryReport extends ReportBase { + constructor(opts) { + super(); + + this.file = opts.file || 'coverage-summary.json'; + this.contentWriter = null; + this.first = true; + } + + onStart(root, context) { + this.contentWriter = context.writer.writeFile(this.file); + this.contentWriter.write('{'); + } + + writeSummary(filePath, sc) { + const cw = this.contentWriter; + if (this.first) { + this.first = false; + } else { + cw.write(','); + } + cw.write(JSON.stringify(filePath)); + cw.write(': '); + cw.write(JSON.stringify(sc)); + cw.println(''); + } + + onSummary(node) { + if (!node.isRoot()) { + return; + } + this.writeSummary('total', node.getCoverageSummary()); + } + + onDetail(node) { + this.writeSummary( + node.getFileCoverage().path, + node.getCoverageSummary() + ); + } + + onEnd() { + const cw = this.contentWriter; + cw.println('}'); + cw.close(); + } +} + +module.exports = JsonSummaryReport; diff --git a/node_modules/istanbul-reports/lib/json/index.js b/node_modules/istanbul-reports/lib/json/index.js new file mode 100644 index 0000000..bcae6ae --- /dev/null +++ b/node_modules/istanbul-reports/lib/json/index.js @@ -0,0 +1,44 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +class JsonReport extends ReportBase { + constructor(opts) { + super(); + + this.file = opts.file || 'coverage-final.json'; + this.first = true; + } + + onStart(root, context) { + this.contentWriter = context.writer.writeFile(this.file); + this.contentWriter.write('{'); + } + + onDetail(node) { + const fc = node.getFileCoverage(); + const key = fc.path; + const cw = this.contentWriter; + + if (this.first) { + this.first = false; + } else { + cw.write(','); + } + cw.write(JSON.stringify(key)); + cw.write(': '); + cw.write(JSON.stringify(fc)); + cw.println(''); + } + + onEnd() { + const cw = this.contentWriter; + cw.println('}'); + cw.close(); + } +} + +module.exports = JsonReport; diff --git a/node_modules/istanbul-reports/lib/lcov/index.js b/node_modules/istanbul-reports/lib/lcov/index.js new file mode 100644 index 0000000..383c202 --- /dev/null +++ b/node_modules/istanbul-reports/lib/lcov/index.js @@ -0,0 +1,33 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const { ReportBase } = require('istanbul-lib-report'); +const LcovOnlyReport = require('../lcovonly'); +const HtmlReport = require('../html'); + +class LcovReport extends ReportBase { + constructor(opts) { + super(); + this.lcov = new LcovOnlyReport({ file: 'lcov.info', ...opts }); + this.html = new HtmlReport({ subdir: 'lcov-report' }); + } +} + +['Start', 'End', 'Summary', 'SummaryEnd', 'Detail'].forEach(what => { + const meth = 'on' + what; + LcovReport.prototype[meth] = function(...args) { + const lcov = this.lcov; + const html = this.html; + + if (lcov[meth]) { + lcov[meth](...args); + } + if (html[meth]) { + html[meth](...args); + } + }; +}); + +module.exports = LcovReport; diff --git a/node_modules/istanbul-reports/lib/lcovonly/index.js b/node_modules/istanbul-reports/lib/lcovonly/index.js new file mode 100644 index 0000000..0720e46 --- /dev/null +++ b/node_modules/istanbul-reports/lib/lcovonly/index.js @@ -0,0 +1,77 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +class LcovOnlyReport extends ReportBase { + constructor(opts) { + super(); + opts = opts || {}; + this.file = opts.file || 'lcov.info'; + this.projectRoot = opts.projectRoot || process.cwd(); + this.contentWriter = null; + } + + onStart(root, context) { + this.contentWriter = context.writer.writeFile(this.file); + } + + onDetail(node) { + const fc = node.getFileCoverage(); + const writer = this.contentWriter; + const functions = fc.f; + const functionMap = fc.fnMap; + const lines = fc.getLineCoverage(); + const branches = fc.b; + const branchMap = fc.branchMap; + const summary = node.getCoverageSummary(); + const path = require('path'); + + writer.println('TN:'); + const fileName = path.relative(this.projectRoot, fc.path); + writer.println('SF:' + fileName); + + Object.values(functionMap).forEach(meta => { + // Some versions of the instrumenter in the wild populate 'loc' + // but not 'decl': + const decl = meta.decl || meta.loc; + writer.println('FN:' + [decl.start.line, meta.name].join(',')); + }); + writer.println('FNF:' + summary.functions.total); + writer.println('FNH:' + summary.functions.covered); + + Object.entries(functionMap).forEach(([key, meta]) => { + const stats = functions[key]; + writer.println('FNDA:' + [stats, meta.name].join(',')); + }); + + Object.entries(lines).forEach(entry => { + writer.println('DA:' + entry.join(',')); + }); + writer.println('LF:' + summary.lines.total); + writer.println('LH:' + summary.lines.covered); + + Object.entries(branches).forEach(([key, branchArray]) => { + const meta = branchMap[key]; + if (meta) { + const { line } = meta.loc.start; + branchArray.forEach((b, i) => { + writer.println('BRDA:' + [line, key, i, b].join(',')); + }); + } else { + console.warn('Missing coverage entries in', fileName, key); + } + }); + writer.println('BRF:' + summary.branches.total); + writer.println('BRH:' + summary.branches.covered); + writer.println('end_of_record'); + } + + onEnd() { + this.contentWriter.close(); + } +} + +module.exports = LcovOnlyReport; diff --git a/node_modules/istanbul-reports/lib/none/index.js b/node_modules/istanbul-reports/lib/none/index.js new file mode 100644 index 0000000..81c1408 --- /dev/null +++ b/node_modules/istanbul-reports/lib/none/index.js @@ -0,0 +1,10 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const { ReportBase } = require('istanbul-lib-report'); + +class NoneReport extends ReportBase {} + +module.exports = NoneReport; diff --git a/node_modules/istanbul-reports/lib/teamcity/index.js b/node_modules/istanbul-reports/lib/teamcity/index.js new file mode 100644 index 0000000..2bca26a --- /dev/null +++ b/node_modules/istanbul-reports/lib/teamcity/index.js @@ -0,0 +1,67 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +class TeamcityReport extends ReportBase { + constructor(opts) { + super(); + + opts = opts || {}; + this.file = opts.file || null; + this.blockName = opts.blockName || 'Code Coverage Summary'; + } + + onStart(node, context) { + const metrics = node.getCoverageSummary(); + const cw = context.writer.writeFile(this.file); + + cw.println(''); + cw.println("##teamcity[blockOpened name='" + this.blockName + "']"); + + //Statements Covered + cw.println( + lineForKey(metrics.statements.covered, 'CodeCoverageAbsBCovered') + ); + cw.println( + lineForKey(metrics.statements.total, 'CodeCoverageAbsBTotal') + ); + + //Branches Covered + cw.println( + lineForKey(metrics.branches.covered, 'CodeCoverageAbsRCovered') + ); + cw.println(lineForKey(metrics.branches.total, 'CodeCoverageAbsRTotal')); + + //Functions Covered + cw.println( + lineForKey(metrics.functions.covered, 'CodeCoverageAbsMCovered') + ); + cw.println( + lineForKey(metrics.functions.total, 'CodeCoverageAbsMTotal') + ); + + //Lines Covered + cw.println( + lineForKey(metrics.lines.covered, 'CodeCoverageAbsLCovered') + ); + cw.println(lineForKey(metrics.lines.total, 'CodeCoverageAbsLTotal')); + + cw.println("##teamcity[blockClosed name='" + this.blockName + "']"); + cw.close(); + } +} + +function lineForKey(value, teamcityVar) { + return ( + "##teamcity[buildStatisticValue key='" + + teamcityVar + + "' value='" + + value + + "']" + ); +} + +module.exports = TeamcityReport; diff --git a/node_modules/istanbul-reports/lib/text-lcov/index.js b/node_modules/istanbul-reports/lib/text-lcov/index.js new file mode 100644 index 0000000..847aedf --- /dev/null +++ b/node_modules/istanbul-reports/lib/text-lcov/index.js @@ -0,0 +1,17 @@ +'use strict'; +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +const LcovOnly = require('../lcovonly'); + +class TextLcov extends LcovOnly { + constructor(opts) { + super({ + ...opts, + file: '-' + }); + } +} + +module.exports = TextLcov; diff --git a/node_modules/istanbul-reports/lib/text-summary/index.js b/node_modules/istanbul-reports/lib/text-summary/index.js new file mode 100644 index 0000000..a9e6eab --- /dev/null +++ b/node_modules/istanbul-reports/lib/text-summary/index.js @@ -0,0 +1,62 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +class TextSummaryReport extends ReportBase { + constructor(opts) { + super(); + + opts = opts || {}; + this.file = opts.file || null; + } + + onStart(node, context) { + const summary = node.getCoverageSummary(); + const cw = context.writer.writeFile(this.file); + const printLine = function(key) { + const str = lineForKey(summary, key); + const clazz = context.classForPercent(key, summary[key].pct); + cw.println(cw.colorize(str, clazz)); + }; + + cw.println(''); + cw.println( + '=============================== Coverage summary ===============================' + ); + printLine('statements'); + printLine('branches'); + printLine('functions'); + printLine('lines'); + cw.println( + '================================================================================' + ); + cw.close(); + } +} + +function lineForKey(summary, key) { + const metrics = summary[key]; + + key = key.substring(0, 1).toUpperCase() + key.substring(1); + if (key.length < 12) { + key += ' '.substring(0, 12 - key.length); + } + const result = [ + key, + ':', + metrics.pct + '%', + '(', + metrics.covered + '/' + metrics.total, + ')' + ].join(' '); + const skipped = metrics.skipped; + if (skipped > 0) { + return result + ', ' + skipped + ' ignored'; + } + return result; +} + +module.exports = TextSummaryReport; diff --git a/node_modules/istanbul-reports/lib/text/index.js b/node_modules/istanbul-reports/lib/text/index.js new file mode 100644 index 0000000..c28cedb --- /dev/null +++ b/node_modules/istanbul-reports/lib/text/index.js @@ -0,0 +1,298 @@ +/* + Copyright 2012-2015, Yahoo Inc. + Copyrights licensed under the New BSD License. See the accompanying LICENSE + file for terms. + */ +'use strict'; +const { ReportBase } = require('istanbul-lib-report'); + +const NAME_COL = 4; +const PCT_COLS = 7; +const MISSING_COL = 17; +const TAB_SIZE = 1; +const DELIM = ' | '; + +function padding(num, ch) { + let str = ''; + let i; + ch = ch || ' '; + for (i = 0; i < num; i += 1) { + str += ch; + } + return str; +} + +function fill(str, width, right, tabs) { + tabs = tabs || 0; + str = String(str); + + const leadingSpaces = tabs * TAB_SIZE; + const remaining = width - leadingSpaces; + const leader = padding(leadingSpaces); + let fmtStr = ''; + + if (remaining > 0) { + const strlen = str.length; + let fillStr; + + if (remaining >= strlen) { + fillStr = padding(remaining - strlen); + } else { + fillStr = '...'; + const length = remaining - fillStr.length; + + str = str.substring(strlen - length); + right = true; + } + fmtStr = right ? fillStr + str : str + fillStr; + } + + return leader + fmtStr; +} + +function formatName(name, maxCols, level) { + return fill(name, maxCols, false, level); +} + +function formatPct(pct, width) { + return fill(pct, width || PCT_COLS, true, 0); +} + +function nodeMissing(node) { + if (node.isSummary()) { + return ''; + } + + const metrics = node.getCoverageSummary(); + const isEmpty = metrics.isEmpty(); + const lines = isEmpty ? 0 : metrics.lines.pct; + + let coveredLines; + + const fileCoverage = node.getFileCoverage(); + if (lines === 100) { + const branches = fileCoverage.getBranchCoverageByLine(); + coveredLines = Object.entries(branches).map(([key, { coverage }]) => [ + key, + coverage === 100 + ]); + } else { + coveredLines = Object.entries(fileCoverage.getLineCoverage()); + } + + let newRange = true; + const ranges = coveredLines + .reduce((acum, [line, hit]) => { + if (hit) newRange = true; + else { + line = parseInt(line); + if (newRange) { + acum.push([line]); + newRange = false; + } else acum[acum.length - 1][1] = line; + } + + return acum; + }, []) + .map(range => { + const { length } = range; + + if (length === 1) return range[0]; + + return `${range[0]}-${range[1]}`; + }); + + return [].concat(...ranges).join(','); +} + +function nodeName(node) { + return node.getRelativeName() || 'All files'; +} + +function depthFor(node) { + let ret = 0; + node = node.getParent(); + while (node) { + ret += 1; + node = node.getParent(); + } + return ret; +} + +function nullDepthFor() { + return 0; +} + +function findWidth(node, context, nodeExtractor, depthFor = nullDepthFor) { + let last = 0; + function compareWidth(node) { + last = Math.max( + last, + TAB_SIZE * depthFor(node) + nodeExtractor(node).length + ); + } + const visitor = { + onSummary: compareWidth, + onDetail: compareWidth + }; + node.visit(context.getVisitor(visitor)); + return last; +} + +function makeLine(nameWidth, missingWidth) { + const name = padding(nameWidth, '-'); + const pct = padding(PCT_COLS, '-'); + const elements = []; + + elements.push(name); + elements.push(pct); + elements.push(padding(PCT_COLS + 1, '-')); + elements.push(pct); + elements.push(pct); + elements.push(padding(missingWidth, '-')); + return elements.join(DELIM.replace(/ /g, '-')) + '-'; +} + +function tableHeader(maxNameCols, missingWidth) { + const elements = []; + elements.push(formatName('File', maxNameCols, 0)); + elements.push(formatPct('% Stmts')); + elements.push(formatPct('% Branch', PCT_COLS + 1)); + elements.push(formatPct('% Funcs')); + elements.push(formatPct('% Lines')); + elements.push(formatName('Uncovered Line #s', missingWidth)); + return elements.join(DELIM) + ' '; +} + +function isFull(metrics) { + return ( + metrics.statements.pct === 100 && + metrics.branches.pct === 100 && + metrics.functions.pct === 100 && + metrics.lines.pct === 100 + ); +} + +function tableRow( + node, + context, + colorizer, + maxNameCols, + level, + skipEmpty, + skipFull, + missingWidth +) { + const name = nodeName(node); + const metrics = node.getCoverageSummary(); + const isEmpty = metrics.isEmpty(); + if (skipEmpty && isEmpty) { + return ''; + } + if (skipFull && isFull(metrics)) { + return ''; + } + + const mm = { + statements: isEmpty ? 0 : metrics.statements.pct, + branches: isEmpty ? 0 : metrics.branches.pct, + functions: isEmpty ? 0 : metrics.functions.pct, + lines: isEmpty ? 0 : metrics.lines.pct + }; + const colorize = isEmpty + ? function(str) { + return str; + } + : function(str, key) { + return colorizer(str, context.classForPercent(key, mm[key])); + }; + const elements = []; + + elements.push(colorize(formatName(name, maxNameCols, level), 'statements')); + elements.push(colorize(formatPct(mm.statements), 'statements')); + elements.push(colorize(formatPct(mm.branches, PCT_COLS + 1), 'branches')); + elements.push(colorize(formatPct(mm.functions), 'functions')); + elements.push(colorize(formatPct(mm.lines), 'lines')); + elements.push( + colorizer( + formatName(nodeMissing(node), missingWidth), + mm.lines === 100 ? 'medium' : 'low' + ) + ); + + return elements.join(DELIM) + ' '; +} + +class TextReport extends ReportBase { + constructor(opts) { + super(opts); + + opts = opts || {}; + const { maxCols } = opts; + + this.file = opts.file || null; + this.maxCols = maxCols != null ? maxCols : process.stdout.columns || 80; + this.cw = null; + this.skipEmpty = opts.skipEmpty; + this.skipFull = opts.skipFull; + } + + onStart(root, context) { + this.cw = context.writer.writeFile(this.file); + this.nameWidth = Math.max( + NAME_COL, + findWidth(root, context, nodeName, depthFor) + ); + this.missingWidth = Math.max( + MISSING_COL, + findWidth(root, context, nodeMissing) + ); + + if (this.maxCols > 0) { + const pct_cols = DELIM.length + 4 * (PCT_COLS + DELIM.length) + 2; + + const maxRemaining = this.maxCols - (pct_cols + MISSING_COL); + if (this.nameWidth > maxRemaining) { + this.nameWidth = maxRemaining; + this.missingWidth = MISSING_COL; + } else if (this.nameWidth < maxRemaining) { + const maxRemaining = this.maxCols - (this.nameWidth + pct_cols); + if (this.missingWidth > maxRemaining) { + this.missingWidth = maxRemaining; + } + } + } + const line = makeLine(this.nameWidth, this.missingWidth); + this.cw.println(line); + this.cw.println(tableHeader(this.nameWidth, this.missingWidth)); + this.cw.println(line); + } + + onSummary(node, context) { + const nodeDepth = depthFor(node); + const row = tableRow( + node, + context, + this.cw.colorize.bind(this.cw), + this.nameWidth, + nodeDepth, + this.skipEmpty, + this.skipFull, + this.missingWidth + ); + if (row) { + this.cw.println(row); + } + } + + onDetail(node, context) { + return this.onSummary(node, context); + } + + onEnd() { + this.cw.println(makeLine(this.nameWidth, this.missingWidth)); + this.cw.close(); + } +} + +module.exports = TextReport; diff --git a/node_modules/istanbul-reports/package.json b/node_modules/istanbul-reports/package.json new file mode 100644 index 0000000..442310f --- /dev/null +++ b/node_modules/istanbul-reports/package.json @@ -0,0 +1,60 @@ +{ + "name": "istanbul-reports", + "version": "3.1.5", + "description": "istanbul reports", + "author": "Krishnan Anantheswaran ", + "main": "index.js", + "files": [ + "index.js", + "lib" + ], + "scripts": { + "test": "nyc mocha --recursive", + "prepare": "webpack --config lib/html-spa/webpack.config.js --mode production", + "prepare:watch": "webpack --config lib/html-spa/webpack.config.js --watch --mode development" + }, + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "devDependencies": { + "@babel/core": "^7.7.5", + "@babel/preset-env": "^7.7.5", + "@babel/preset-react": "^7.7.4", + "babel-loader": "^8.0.6", + "chai": "^4.2.0", + "is-windows": "^1.0.2", + "istanbul-lib-coverage": "^3.0.0", + "mocha": "^6.2.2", + "nyc": "^15.0.0-beta.2", + "react": "^16.12.0", + "react-dom": "^16.12.0", + "webpack": "^4.41.2", + "webpack-cli": "^3.3.10" + }, + "license": "BSD-3-Clause", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/istanbuljs/istanbuljs.git", + "directory": "packages/istanbul-reports" + }, + "keywords": [ + "istanbul", + "reports" + ], + "bugs": { + "url": "https://github.com/istanbuljs/istanbuljs/issues" + }, + "homepage": "https://istanbul.js.org/", + "nyc": { + "exclude": [ + "lib/html/assets/**", + "lib/html-spa/assets/**", + "lib/html-spa/rollup.config.js", + "test/**" + ] + }, + "engines": { + "node": ">=8" + } +} diff --git a/node_modules/jest-changed-files/LICENSE b/node_modules/jest-changed-files/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-changed-files/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-changed-files/README.md b/node_modules/jest-changed-files/README.md new file mode 100644 index 0000000..d0c8539 --- /dev/null +++ b/node_modules/jest-changed-files/README.md @@ -0,0 +1,63 @@ +# jest-changed-files + +A module used internally by Jest to check which files have changed since you last committed in git or hg. + +## Install + +```sh +$ npm install --save jest-changed-files +``` + +## API + +### `getChangedFilesForRoots(roots: >, options: ?object): Promise` + +Get the list of files and repos that have changed since the last commit. + +#### Parameters + +roots: Array of string paths gathered from [jest roots](https://jestjs.io/docs/configuration#roots-arraystring). + +options: Object literal with keys + +- lastCommit: boolean +- withAncestor: boolean + +### findRepos(roots: >): Promise + +Get a set of git and hg repositories. + +#### Parameters + +roots: Array of string paths gathered from [jest roots](https://jestjs.io/docs/configuration#roots-arraystring). + +## Usage + +```javascript +import {getChangedFilesForRoots} from 'jest-changed-files'; + +getChangedFilesForRoots(['/path/to/test'], { + lastCommit: true, + withAncestor: true, +}).then(files => { + /* + { + repos: [], + changedFiles: [] + } + */ +}); +``` + +```javascript +import {findRepos} from 'jest-changed-files'; + +findRepos(['/path/to/test']).then(repos => { + /* + { + git: Set, + hg: Set + } + */ +}); +``` diff --git a/node_modules/jest-changed-files/build/git.js b/node_modules/jest-changed-files/build/git.js new file mode 100644 index 0000000..069e8ff --- /dev/null +++ b/node_modules/jest-changed-files/build/git.js @@ -0,0 +1,169 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _util() { + const data = require('util'); + _util = function () { + return data; + }; + return data; +} +function _execa() { + const data = _interopRequireDefault(require('execa')); + _execa = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +const findChangedFilesUsingCommand = async (args, cwd) => { + let result; + try { + result = await (0, _execa().default)('git', args, { + cwd + }); + } catch (e) { + if (_util().types.isNativeError(e)) { + const err = e; + // TODO: Should we keep the original `message`? + err.message = err.stderr; + } + throw e; + } + return result.stdout + .split('\n') + .filter(s => s !== '') + .map(changedPath => path().resolve(cwd, changedPath)); +}; +const adapter = { + findChangedFiles: async (cwd, options) => { + const changedSince = + options.withAncestor === true ? 'HEAD^' : options.changedSince; + const includePaths = (options.includePaths ?? []).map(absoluteRoot => + path().normalize(path().relative(cwd, absoluteRoot)) + ); + if (options.lastCommit === true) { + return findChangedFilesUsingCommand( + ['show', '--name-only', '--pretty=format:', 'HEAD', '--'].concat( + includePaths + ), + cwd + ); + } + if (changedSince != null && changedSince.length > 0) { + const [committed, staged, unstaged] = await Promise.all([ + findChangedFilesUsingCommand( + ['diff', '--name-only', `${changedSince}...HEAD`, '--'].concat( + includePaths + ), + cwd + ), + findChangedFilesUsingCommand( + ['diff', '--cached', '--name-only', '--'].concat(includePaths), + cwd + ), + findChangedFilesUsingCommand( + [ + 'ls-files', + '--other', + '--modified', + '--exclude-standard', + '--' + ].concat(includePaths), + cwd + ) + ]); + return [...committed, ...staged, ...unstaged]; + } + const [staged, unstaged] = await Promise.all([ + findChangedFilesUsingCommand( + ['diff', '--cached', '--name-only', '--'].concat(includePaths), + cwd + ), + findChangedFilesUsingCommand( + [ + 'ls-files', + '--other', + '--modified', + '--exclude-standard', + '--' + ].concat(includePaths), + cwd + ) + ]); + return [...staged, ...unstaged]; + }, + getRoot: async cwd => { + const options = ['rev-parse', '--show-cdup']; + try { + const result = await (0, _execa().default)('git', options, { + cwd + }); + return path().resolve(cwd, result.stdout); + } catch { + return null; + } + } +}; +var _default = adapter; +exports.default = _default; diff --git a/node_modules/jest-changed-files/build/hg.js b/node_modules/jest-changed-files/build/hg.js new file mode 100644 index 0000000..19b5dfb --- /dev/null +++ b/node_modules/jest-changed-files/build/hg.js @@ -0,0 +1,130 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _util() { + const data = require('util'); + _util = function () { + return data; + }; + return data; +} +function _execa() { + const data = _interopRequireDefault(require('execa')); + _execa = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +const env = { + ...process.env, + HGPLAIN: '1' +}; +const adapter = { + findChangedFiles: async (cwd, options) => { + const includePaths = options.includePaths ?? []; + const args = ['status', '-amnu']; + if (options.withAncestor === true) { + args.push('--rev', 'first(min(!public() & ::.)^+.^)'); + } else if ( + options.changedSince != null && + options.changedSince.length > 0 + ) { + args.push('--rev', `ancestor(., ${options.changedSince})`); + } else if (options.lastCommit === true) { + args.push('--change', '.'); + } + args.push(...includePaths); + let result; + try { + result = await (0, _execa().default)('hg', args, { + cwd, + env + }); + } catch (e) { + if (_util().types.isNativeError(e)) { + const err = e; + // TODO: Should we keep the original `message`? + err.message = err.stderr; + } + throw e; + } + return result.stdout + .split('\n') + .filter(s => s !== '') + .map(changedPath => path().resolve(cwd, changedPath)); + }, + getRoot: async cwd => { + try { + const result = await (0, _execa().default)('hg', ['root'], { + cwd, + env + }); + return result.stdout; + } catch { + return null; + } + } +}; +var _default = adapter; +exports.default = _default; diff --git a/node_modules/jest-changed-files/build/index.d.ts b/node_modules/jest-changed-files/build/index.d.ts new file mode 100644 index 0000000..9dc1e76 --- /dev/null +++ b/node_modules/jest-changed-files/build/index.d.ts @@ -0,0 +1,35 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare type ChangedFiles = { + repos: Repos; + changedFiles: Paths; +}; + +export declare type ChangedFilesPromise = Promise; + +export declare const findRepos: (roots: Array) => Promise; + +export declare const getChangedFilesForRoots: ( + roots: Array, + options: Options, +) => ChangedFilesPromise; + +declare type Options = { + lastCommit?: boolean; + withAncestor?: boolean; + changedSince?: string; + includePaths?: Array; +}; + +declare type Paths = Set; + +declare type Repos = { + git: Paths; + hg: Paths; +}; + +export {}; diff --git a/node_modules/jest-changed-files/build/index.js b/node_modules/jest-changed-files/build/index.js new file mode 100644 index 0000000..15c2ac9 --- /dev/null +++ b/node_modules/jest-changed-files/build/index.js @@ -0,0 +1,74 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getChangedFilesForRoots = exports.findRepos = void 0; +function _pLimit() { + const data = _interopRequireDefault(require('p-limit')); + _pLimit = function () { + return data; + }; + return data; +} +var _git = _interopRequireDefault(require('./git')); +var _hg = _interopRequireDefault(require('./hg')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +function notEmpty(value) { + return value != null; +} + +// This is an arbitrary number. The main goal is to prevent projects with +// many roots (50+) from spawning too many processes at once. +const mutex = (0, _pLimit().default)(5); +const findGitRoot = dir => mutex(() => _git.default.getRoot(dir)); +const findHgRoot = dir => mutex(() => _hg.default.getRoot(dir)); +const getChangedFilesForRoots = async (roots, options) => { + const repos = await findRepos(roots); + const changedFilesOptions = { + includePaths: roots, + ...options + }; + const gitPromises = Array.from(repos.git).map(repo => + _git.default.findChangedFiles(repo, changedFilesOptions) + ); + const hgPromises = Array.from(repos.hg).map(repo => + _hg.default.findChangedFiles(repo, changedFilesOptions) + ); + const changedFiles = ( + await Promise.all(gitPromises.concat(hgPromises)) + ).reduce((allFiles, changedFilesInTheRepo) => { + for (const file of changedFilesInTheRepo) { + allFiles.add(file); + } + return allFiles; + }, new Set()); + return { + changedFiles, + repos + }; +}; +exports.getChangedFilesForRoots = getChangedFilesForRoots; +const findRepos = async roots => { + const gitRepos = await Promise.all( + roots.reduce((promises, root) => promises.concat(findGitRoot(root)), []) + ); + const hgRepos = await Promise.all( + roots.reduce((promises, root) => promises.concat(findHgRoot(root)), []) + ); + return { + git: new Set(gitRepos.filter(notEmpty)), + hg: new Set(hgRepos.filter(notEmpty)) + }; +}; +exports.findRepos = findRepos; diff --git a/node_modules/jest-changed-files/build/types.js b/node_modules/jest-changed-files/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-changed-files/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-changed-files/package.json b/node_modules/jest-changed-files/package.json new file mode 100644 index 0000000..e896112 --- /dev/null +++ b/node_modules/jest-changed-files/package.json @@ -0,0 +1,30 @@ +{ + "name": "jest-changed-files", + "version": "29.2.0", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-changed-files" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "execa": "^5.0.0", + "p-limit": "^3.1.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "ee5b37a4f4433afcfffb0356cea47739d8092287" +} diff --git a/node_modules/jest-circus/LICENSE b/node_modules/jest-circus/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-circus/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-circus/README.md b/node_modules/jest-circus/README.md new file mode 100644 index 0000000..75a2f77 --- /dev/null +++ b/node_modules/jest-circus/README.md @@ -0,0 +1,65 @@ +[type-definitions]: https://github.com/facebook/jest/blob/main/packages/jest-types/src/Circus.ts + +

+ + +

jest-circus

+

The next-gen test runner for Jest

+

+ +## Overview + +Circus is a flux-based test runner for Jest that is fast, maintainable, and simple to extend. + +Circus allows you to bind to events via an optional event handler on any [custom environment](https://jestjs.io/docs/configuration#testenvironment-string). See the [type definitions][type-definitions] for more information on the events and state data currently available. + +```js +import {Event, State} from 'jest-circus'; +import {TestEnvironment as NodeEnvironment} from 'jest-environment-node'; + +class MyCustomEnvironment extends NodeEnvironment { + //... + + async handleTestEvent(event: Event, state: State) { + if (event.name === 'test_start') { + // ... + } + } +} +``` + +Mutating event or state data is currently unsupported and may cause unexpected behavior or break in a future release without warning. New events, event data, and/or state data will not be considered a breaking change and may be added in any minor release. + +Note, that `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled. **However, there are a few events that do not conform to this rule, namely**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions][type-definitions]). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. + +## Installation + +> Note: As of Jest 27, `jest-circus` is the default test runner, so you do not have to install it to use it. + +Install `jest-circus` using yarn: + +```bash +yarn add --dev jest-circus +``` + +Or via npm: + +```bash +npm install --save-dev jest-circus +``` + +## Configure + +Configure Jest to use `jest-circus` via the [`testRunner`](https://jestjs.io/docs/configuration#testrunner-string) option: + +```json +{ + "testRunner": "jest-circus/runner" +} +``` + +Or via CLI: + +```bash +jest --testRunner='jest-circus/runner' +``` diff --git a/node_modules/jest-circus/build/eventHandler.js b/node_modules/jest-circus/build/eventHandler.js new file mode 100644 index 0000000..013bbfc --- /dev/null +++ b/node_modules/jest-circus/build/eventHandler.js @@ -0,0 +1,271 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _globalErrorHandlers = require('./globalErrorHandlers'); +var _types = require('./types'); +var _utils = require('./utils'); +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestNow = globalThis[Symbol.for('jest-native-now')] || globalThis.Date.now; +const eventHandler = (event, state) => { + switch (event.name) { + case 'include_test_location_in_result': { + state.includeTestLocationInResult = true; + break; + } + case 'hook_start': { + event.hook.seenDone = false; + break; + } + case 'start_describe_definition': { + const {blockName, mode} = event; + const {currentDescribeBlock, currentlyRunningTest} = state; + if (currentlyRunningTest) { + currentlyRunningTest.errors.push( + new Error( + `Cannot nest a describe inside a test. Describe block "${blockName}" cannot run because it is nested within "${currentlyRunningTest.name}".` + ) + ); + break; + } + const describeBlock = (0, _utils.makeDescribe)( + blockName, + currentDescribeBlock, + mode + ); + currentDescribeBlock.children.push(describeBlock); + state.currentDescribeBlock = describeBlock; + break; + } + case 'finish_describe_definition': { + const {currentDescribeBlock} = state; + (0, _utils.invariant)( + currentDescribeBlock, + 'currentDescribeBlock must be there' + ); + if (!(0, _utils.describeBlockHasTests)(currentDescribeBlock)) { + currentDescribeBlock.hooks.forEach(hook => { + hook.asyncError.message = `Invalid: ${hook.type}() may not be used in a describe block containing no tests.`; + state.unhandledErrors.push(hook.asyncError); + }); + } + + // pass mode of currentDescribeBlock to tests + // but do not when there is already a single test with "only" mode + const shouldPassMode = !( + currentDescribeBlock.mode === 'only' && + currentDescribeBlock.children.some( + child => child.type === 'test' && child.mode === 'only' + ) + ); + if (shouldPassMode) { + currentDescribeBlock.children.forEach(child => { + if (child.type === 'test' && !child.mode) { + child.mode = currentDescribeBlock.mode; + } + }); + } + if ( + !state.hasFocusedTests && + currentDescribeBlock.mode !== 'skip' && + currentDescribeBlock.children.some( + child => child.type === 'test' && child.mode === 'only' + ) + ) { + state.hasFocusedTests = true; + } + if (currentDescribeBlock.parent) { + state.currentDescribeBlock = currentDescribeBlock.parent; + } + break; + } + case 'add_hook': { + const {currentDescribeBlock, currentlyRunningTest, hasStarted} = state; + const {asyncError, fn, hookType: type, timeout} = event; + if (currentlyRunningTest) { + currentlyRunningTest.errors.push( + new Error( + `Hooks cannot be defined inside tests. Hook of type "${type}" is nested within "${currentlyRunningTest.name}".` + ) + ); + break; + } else if (hasStarted) { + state.unhandledErrors.push( + new Error( + 'Cannot add a hook after tests have started running. Hooks must be defined synchronously.' + ) + ); + break; + } + const parent = currentDescribeBlock; + currentDescribeBlock.hooks.push({ + asyncError, + fn, + parent, + seenDone: false, + timeout, + type + }); + break; + } + case 'add_test': { + const {currentDescribeBlock, currentlyRunningTest, hasStarted} = state; + const { + asyncError, + fn, + mode, + testName: name, + timeout, + concurrent, + failing + } = event; + if (currentlyRunningTest) { + currentlyRunningTest.errors.push( + new Error( + `Tests cannot be nested. Test "${name}" cannot run because it is nested within "${currentlyRunningTest.name}".` + ) + ); + break; + } else if (hasStarted) { + state.unhandledErrors.push( + new Error( + 'Cannot add a test after tests have started running. Tests must be defined synchronously.' + ) + ); + break; + } + const test = (0, _utils.makeTest)( + fn, + mode, + concurrent, + name, + currentDescribeBlock, + timeout, + asyncError, + failing + ); + if (currentDescribeBlock.mode !== 'skip' && test.mode === 'only') { + state.hasFocusedTests = true; + } + currentDescribeBlock.children.push(test); + currentDescribeBlock.tests.push(test); + break; + } + case 'hook_failure': { + const {test, describeBlock, error, hook} = event; + const {asyncError, type} = hook; + if (type === 'beforeAll') { + (0, _utils.invariant)(describeBlock, 'always present for `*All` hooks'); + (0, _utils.addErrorToEachTestUnderDescribe)( + describeBlock, + error, + asyncError + ); + } else if (type === 'afterAll') { + // Attaching `afterAll` errors to each test makes execution flow + // too complicated, so we'll consider them to be global. + state.unhandledErrors.push([error, asyncError]); + } else { + (0, _utils.invariant)(test, 'always present for `*Each` hooks'); + test.errors.push([error, asyncError]); + } + break; + } + case 'test_skip': { + event.test.status = 'skip'; + break; + } + case 'test_todo': { + event.test.status = 'todo'; + break; + } + case 'test_done': { + event.test.duration = (0, _utils.getTestDuration)(event.test); + event.test.status = 'done'; + state.currentlyRunningTest = null; + break; + } + case 'test_start': { + state.currentlyRunningTest = event.test; + event.test.startedAt = jestNow(); + event.test.invocations += 1; + break; + } + case 'test_fn_start': { + event.test.seenDone = false; + break; + } + case 'test_fn_failure': { + const { + error, + test: {asyncError} + } = event; + event.test.errors.push([error, asyncError]); + break; + } + case 'test_retry': { + const logErrorsBeforeRetry = + // eslint-disable-next-line no-restricted-globals + global[_types.LOG_ERRORS_BEFORE_RETRY] || false; + if (logErrorsBeforeRetry) { + event.test.retryReasons.push(...event.test.errors); + } + event.test.errors = []; + break; + } + case 'run_start': { + state.hasStarted = true; + /* eslint-disable no-restricted-globals */ + global[_types.TEST_TIMEOUT_SYMBOL] && + (state.testTimeout = global[_types.TEST_TIMEOUT_SYMBOL]); + /* eslint-enable */ + break; + } + case 'run_finish': { + break; + } + case 'setup': { + // Uncaught exception handlers should be defined on the parent process + // object. If defined on the VM's process object they just no op and let + // the parent process crash. It might make sense to return a `dispatch` + // function to the parent process and register handlers there instead, but + // i'm not sure if this is works. For now i just replicated whatever + // jasmine was doing -- dabramov + state.parentProcess = event.parentProcess; + (0, _utils.invariant)(state.parentProcess); + state.originalGlobalErrorHandlers = (0, + _globalErrorHandlers.injectGlobalErrorHandlers)(state.parentProcess); + if (event.testNamePattern) { + state.testNamePattern = new RegExp(event.testNamePattern, 'i'); + } + break; + } + case 'teardown': { + (0, _utils.invariant)(state.originalGlobalErrorHandlers); + (0, _utils.invariant)(state.parentProcess); + (0, _globalErrorHandlers.restoreGlobalErrorHandlers)( + state.parentProcess, + state.originalGlobalErrorHandlers + ); + break; + } + case 'error': { + // It's very likely for long-running async tests to throw errors. In this + // case we want to catch them and fail the current test. At the same time + // there's a possibility that one test sets a long timeout, that will + // eventually throw after this test finishes but during some other test + // execution, which will result in one test's error failing another test. + // In any way, it should be possible to track where the error was thrown + // from. + state.currentlyRunningTest + ? state.currentlyRunningTest.errors.push(event.error) + : state.unhandledErrors.push(event.error); + break; + } + } +}; +var _default = eventHandler; +exports.default = _default; diff --git a/node_modules/jest-circus/build/formatNodeAssertErrors.js b/node_modules/jest-circus/build/formatNodeAssertErrors.js new file mode 100644 index 0000000..35072f7 --- /dev/null +++ b/node_modules/jest-circus/build/formatNodeAssertErrors.js @@ -0,0 +1,186 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _assert = require('assert'); +var _chalk = _interopRequireDefault(require('chalk')); +var _jestMatcherUtils = require('jest-matcher-utils'); +var _prettyFormat = require('pretty-format'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const assertOperatorsMap = { + '!=': 'notEqual', + '!==': 'notStrictEqual', + '==': 'equal', + '===': 'strictEqual' +}; +const humanReadableOperators = { + deepEqual: 'to deeply equal', + deepStrictEqual: 'to deeply and strictly equal', + equal: 'to be equal', + notDeepEqual: 'not to deeply equal', + notDeepStrictEqual: 'not to deeply and strictly equal', + notEqual: 'to not be equal', + notStrictEqual: 'not be strictly equal', + strictEqual: 'to strictly be equal' +}; +const formatNodeAssertErrors = (event, state) => { + if (event.name === 'test_done') { + event.test.errors = event.test.errors.map(errors => { + let error; + if (Array.isArray(errors)) { + const [originalError, asyncError] = errors; + if (originalError == null) { + error = asyncError; + } else if (!originalError.stack) { + error = asyncError; + error.message = originalError.message + ? originalError.message + : `thrown: ${(0, _prettyFormat.format)(originalError, { + maxDepth: 3 + })}`; + } else { + error = originalError; + } + } else { + error = errors; + } + return isAssertionError(error) + ? { + message: assertionErrorMessage(error, { + expand: state.expand + }) + } + : errors; + }); + } +}; +const getOperatorName = (operator, stack) => { + if (typeof operator === 'string') { + return assertOperatorsMap[operator] || operator; + } + if (stack.match('.doesNotThrow')) { + return 'doesNotThrow'; + } + if (stack.match('.throws')) { + return 'throws'; + } + return ''; +}; +const operatorMessage = operator => { + const niceOperatorName = getOperatorName(operator, ''); + const humanReadableOperator = humanReadableOperators[niceOperatorName]; + return typeof operator === 'string' + ? `${humanReadableOperator || niceOperatorName} to:\n` + : ''; +}; +const assertThrowingMatcherHint = operatorName => + operatorName + ? _chalk.default.dim('assert') + + _chalk.default.dim(`.${operatorName}(`) + + _chalk.default.red('function') + + _chalk.default.dim(')') + : ''; +const assertMatcherHint = (operator, operatorName, expected) => { + let message = ''; + if (operator === '==' && expected === true) { + message = + _chalk.default.dim('assert') + + _chalk.default.dim('(') + + _chalk.default.red('received') + + _chalk.default.dim(')'); + } else if (operatorName) { + message = + _chalk.default.dim('assert') + + _chalk.default.dim(`.${operatorName}(`) + + _chalk.default.red('received') + + _chalk.default.dim(', ') + + _chalk.default.green('expected') + + _chalk.default.dim(')'); + } + return message; +}; +function assertionErrorMessage(error, options) { + const {expected, actual, generatedMessage, message, operator, stack} = error; + const diffString = (0, _jestMatcherUtils.diff)(expected, actual, options); + const hasCustomMessage = !generatedMessage; + const operatorName = getOperatorName(operator, stack); + const trimmedStack = stack + .replace(message, '') + .replace(/AssertionError(.*)/g, ''); + if (operatorName === 'doesNotThrow') { + return ( + // eslint-disable-next-line prefer-template + buildHintString(assertThrowingMatcherHint(operatorName)) + + _chalk.default.reset('Expected the function not to throw an error.\n') + + _chalk.default.reset('Instead, it threw:\n') + + ` ${(0, _jestMatcherUtils.printReceived)(actual)}` + + _chalk.default.reset( + hasCustomMessage ? `\n\nMessage:\n ${message}` : '' + ) + + trimmedStack + ); + } + if (operatorName === 'throws') { + if (error.generatedMessage) { + return ( + buildHintString(assertThrowingMatcherHint(operatorName)) + + _chalk.default.reset(error.message) + + _chalk.default.reset( + hasCustomMessage ? `\n\nMessage:\n ${message}` : '' + ) + + trimmedStack + ); + } + return ( + buildHintString(assertThrowingMatcherHint(operatorName)) + + _chalk.default.reset('Expected the function to throw an error.\n') + + _chalk.default.reset("But it didn't throw anything.") + + _chalk.default.reset( + hasCustomMessage ? `\n\nMessage:\n ${message}` : '' + ) + + trimmedStack + ); + } + if (operatorName === 'fail') { + return ( + buildHintString(assertMatcherHint(operator, operatorName, expected)) + + _chalk.default.reset(hasCustomMessage ? `Message:\n ${message}` : '') + + trimmedStack + ); + } + return ( + // eslint-disable-next-line prefer-template + buildHintString(assertMatcherHint(operator, operatorName, expected)) + + _chalk.default.reset(`Expected value ${operatorMessage(operator)}`) + + ` ${(0, _jestMatcherUtils.printExpected)(expected)}\n` + + _chalk.default.reset('Received:\n') + + ` ${(0, _jestMatcherUtils.printReceived)(actual)}` + + _chalk.default.reset(hasCustomMessage ? `\n\nMessage:\n ${message}` : '') + + (diffString ? `\n\nDifference:\n\n${diffString}` : '') + + trimmedStack + ); +} +function isAssertionError(error) { + return ( + error && + (error instanceof _assert.AssertionError || + error.name === _assert.AssertionError.name || + error.code === 'ERR_ASSERTION') + ); +} +function buildHintString(hint) { + return hint ? `${hint}\n\n` : ''; +} +var _default = formatNodeAssertErrors; +exports.default = _default; diff --git a/node_modules/jest-circus/build/globalErrorHandlers.js b/node_modules/jest-circus/build/globalErrorHandlers.js new file mode 100644 index 0000000..05981ad --- /dev/null +++ b/node_modules/jest-circus/build/globalErrorHandlers.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.restoreGlobalErrorHandlers = exports.injectGlobalErrorHandlers = void 0; +var _state = require('./state'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const uncaught = error => { + (0, _state.dispatchSync)({ + error, + name: 'error' + }); +}; +const injectGlobalErrorHandlers = parentProcess => { + const uncaughtException = process.listeners('uncaughtException').slice(); + const unhandledRejection = process.listeners('unhandledRejection').slice(); + parentProcess.removeAllListeners('uncaughtException'); + parentProcess.removeAllListeners('unhandledRejection'); + parentProcess.on('uncaughtException', uncaught); + parentProcess.on('unhandledRejection', uncaught); + return { + uncaughtException, + unhandledRejection + }; +}; +exports.injectGlobalErrorHandlers = injectGlobalErrorHandlers; +const restoreGlobalErrorHandlers = (parentProcess, originalErrorHandlers) => { + parentProcess.removeListener('uncaughtException', uncaught); + parentProcess.removeListener('unhandledRejection', uncaught); + for (const listener of originalErrorHandlers.uncaughtException) { + parentProcess.on('uncaughtException', listener); + } + for (const listener of originalErrorHandlers.unhandledRejection) { + parentProcess.on('unhandledRejection', listener); + } +}; +exports.restoreGlobalErrorHandlers = restoreGlobalErrorHandlers; diff --git a/node_modules/jest-circus/build/index.d.ts b/node_modules/jest-circus/build/index.d.ts new file mode 100644 index 0000000..6e35768 --- /dev/null +++ b/node_modules/jest-circus/build/index.d.ts @@ -0,0 +1,72 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Circus} from '@jest/types'; +import type {Global} from '@jest/types'; + +export declare const afterAll: THook; + +export declare const afterEach: THook; + +export declare const beforeAll: THook; + +export declare const beforeEach: THook; + +declare const _default: { + afterAll: THook; + afterEach: THook; + beforeAll: THook; + beforeEach: THook; + describe: { + (blockName: Global.BlockNameLike, blockFn: Global.BlockFn): void; + each: Global.EachTestFn; + only: { + (blockName: Global.BlockNameLike, blockFn: Global.BlockFn): void; + each: Global.EachTestFn; + }; + skip: { + (blockName: Global.BlockNameLike, blockFn: Global.BlockFn): void; + each: Global.EachTestFn; + }; + }; + it: Global.It; + test: Global.It; +}; +export default _default; + +export declare const describe: { + (blockName: Circus.BlockNameLike, blockFn: Circus.BlockFn): void; + each: Global.EachTestFn; + only: { + (blockName: Circus.BlockNameLike, blockFn: Circus.BlockFn): void; + each: Global.EachTestFn; + }; + skip: { + (blockName: Circus.BlockNameLike, blockFn: Circus.BlockFn): void; + each: Global.EachTestFn; + }; +}; + +declare type Event_2 = Circus.Event; +export {Event_2 as Event}; + +export declare const getState: () => Circus.State; + +export declare const it: Global.It; + +export declare const resetState: () => void; + +export declare const run: () => Promise; + +export declare const setState: (state: Circus.State) => Circus.State; + +export declare type State = Circus.State; + +export declare const test: Global.It; + +declare type THook = (fn: Circus.HookFn, timeout?: number) => void; + +export {}; diff --git a/node_modules/jest-circus/build/index.js b/node_modules/jest-circus/build/index.js new file mode 100644 index 0000000..9c82777 --- /dev/null +++ b/node_modules/jest-circus/build/index.js @@ -0,0 +1,238 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.describe = + exports.default = + exports.beforeEach = + exports.beforeAll = + exports.afterEach = + exports.afterAll = + void 0; +Object.defineProperty(exports, 'getState', { + enumerable: true, + get: function () { + return _state.getState; + } +}); +exports.it = void 0; +Object.defineProperty(exports, 'resetState', { + enumerable: true, + get: function () { + return _state.resetState; + } +}); +Object.defineProperty(exports, 'run', { + enumerable: true, + get: function () { + return _run.default; + } +}); +Object.defineProperty(exports, 'setState', { + enumerable: true, + get: function () { + return _state.setState; + } +}); +exports.test = void 0; +var _jestEach = require('jest-each'); +var _jestUtil = require('jest-util'); +var _state = require('./state'); +var _run = _interopRequireDefault(require('./run')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const describe = (() => { + const describe = (blockName, blockFn) => + _dispatchDescribe(blockFn, blockName, describe); + const only = (blockName, blockFn) => + _dispatchDescribe(blockFn, blockName, only, 'only'); + const skip = (blockName, blockFn) => + _dispatchDescribe(blockFn, blockName, skip, 'skip'); + describe.each = (0, _jestEach.bind)(describe, false); + only.each = (0, _jestEach.bind)(only, false); + skip.each = (0, _jestEach.bind)(skip, false); + describe.only = only; + describe.skip = skip; + return describe; +})(); +exports.describe = describe; +const _dispatchDescribe = (blockFn, blockName, describeFn, mode) => { + const asyncError = new _jestUtil.ErrorWithStack(undefined, describeFn); + if (blockFn === undefined) { + asyncError.message = + 'Missing second argument. It must be a callback function.'; + throw asyncError; + } + if (typeof blockFn !== 'function') { + asyncError.message = `Invalid second argument, ${blockFn}. It must be a callback function.`; + throw asyncError; + } + try { + blockName = (0, _jestUtil.convertDescriptorToString)(blockName); + } catch (error) { + asyncError.message = error.message; + throw asyncError; + } + (0, _state.dispatchSync)({ + asyncError, + blockName, + mode, + name: 'start_describe_definition' + }); + const describeReturn = blockFn(); + if ((0, _jestUtil.isPromise)(describeReturn)) { + throw new _jestUtil.ErrorWithStack( + 'Returning a Promise from "describe" is not supported. Tests must be defined synchronously.', + describeFn + ); + } else if (describeReturn !== undefined) { + throw new _jestUtil.ErrorWithStack( + 'A "describe" callback must not return a value.', + describeFn + ); + } + (0, _state.dispatchSync)({ + blockName, + mode, + name: 'finish_describe_definition' + }); +}; +const _addHook = (fn, hookType, hookFn, timeout) => { + const asyncError = new _jestUtil.ErrorWithStack(undefined, hookFn); + if (typeof fn !== 'function') { + asyncError.message = + 'Invalid first argument. It must be a callback function.'; + throw asyncError; + } + (0, _state.dispatchSync)({ + asyncError, + fn, + hookType, + name: 'add_hook', + timeout + }); +}; + +// Hooks have to pass themselves to the HOF in order for us to trim stack traces. +const beforeEach = (fn, timeout) => + _addHook(fn, 'beforeEach', beforeEach, timeout); +exports.beforeEach = beforeEach; +const beforeAll = (fn, timeout) => + _addHook(fn, 'beforeAll', beforeAll, timeout); +exports.beforeAll = beforeAll; +const afterEach = (fn, timeout) => + _addHook(fn, 'afterEach', afterEach, timeout); +exports.afterEach = afterEach; +const afterAll = (fn, timeout) => _addHook(fn, 'afterAll', afterAll, timeout); +exports.afterAll = afterAll; +const test = (() => { + const test = (testName, fn, timeout) => + _addTest(testName, undefined, false, fn, test, timeout); + const skip = (testName, fn, timeout) => + _addTest(testName, 'skip', false, fn, skip, timeout); + const only = (testName, fn, timeout) => + _addTest(testName, 'only', false, fn, test.only, timeout); + const concurrentTest = (testName, fn, timeout) => + _addTest(testName, undefined, true, fn, concurrentTest, timeout); + const concurrentOnly = (testName, fn, timeout) => + _addTest(testName, 'only', true, fn, concurrentOnly, timeout); + const bindFailing = (concurrent, mode) => { + const failing = (testName, fn, timeout, eachError) => + _addTest( + testName, + mode, + concurrent, + fn, + failing, + timeout, + true, + eachError + ); + failing.each = (0, _jestEach.bind)(failing, false, true); + return failing; + }; + test.todo = (testName, ...rest) => { + if (rest.length > 0 || typeof testName !== 'string') { + throw new _jestUtil.ErrorWithStack( + 'Todo must be called with only a description.', + test.todo + ); + } + // eslint-disable-next-line @typescript-eslint/no-empty-function + return _addTest(testName, 'todo', false, () => {}, test.todo); + }; + const _addTest = ( + testName, + mode, + concurrent, + fn, + testFn, + timeout, + failing, + asyncError = new _jestUtil.ErrorWithStack(undefined, testFn) + ) => { + try { + testName = (0, _jestUtil.convertDescriptorToString)(testName); + } catch (error) { + asyncError.message = error.message; + throw asyncError; + } + if (fn === undefined) { + asyncError.message = + 'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.'; + throw asyncError; + } + if (typeof fn !== 'function') { + asyncError.message = `Invalid second argument, ${fn}. It must be a callback function.`; + throw asyncError; + } + return (0, _state.dispatchSync)({ + asyncError, + concurrent, + failing: failing === undefined ? false : failing, + fn, + mode, + name: 'add_test', + testName, + timeout + }); + }; + test.each = (0, _jestEach.bind)(test); + only.each = (0, _jestEach.bind)(only); + skip.each = (0, _jestEach.bind)(skip); + concurrentTest.each = (0, _jestEach.bind)(concurrentTest, false); + concurrentOnly.each = (0, _jestEach.bind)(concurrentOnly, false); + only.failing = bindFailing(false, 'only'); + skip.failing = bindFailing(false, 'skip'); + test.failing = bindFailing(false); + test.only = only; + test.skip = skip; + test.concurrent = concurrentTest; + concurrentTest.only = concurrentOnly; + concurrentTest.skip = skip; + concurrentTest.failing = bindFailing(true); + concurrentOnly.failing = bindFailing(true, 'only'); + return test; +})(); +exports.test = test; +const it = test; +exports.it = it; +var _default = { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + it, + test +}; +exports.default = _default; diff --git a/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js b/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js new file mode 100644 index 0000000..dfa0f7d --- /dev/null +++ b/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapter.js @@ -0,0 +1,117 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _jestUtil = require('jest-util'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const FRAMEWORK_INITIALIZER = require.resolve('./jestAdapterInit'); +const jestAdapter = async ( + globalConfig, + config, + environment, + runtime, + testPath, + sendMessageToJest +) => { + const {initialize, runAndTransformResultsToJestFormat} = + runtime.requireInternalModule(FRAMEWORK_INITIALIZER); + const {globals, snapshotState} = await initialize({ + config, + environment, + globalConfig, + localRequire: runtime.requireModule.bind(runtime), + parentProcess: process, + sendMessageToJest, + setGlobalsForRuntime: runtime.setGlobalsForRuntime.bind(runtime), + testPath + }); + if (config.fakeTimers.enableGlobally) { + if (config.fakeTimers.legacyFakeTimers) { + // during setup, this cannot be null (and it's fine to explode if it is) + environment.fakeTimers.useFakeTimers(); + } else { + environment.fakeTimersModern.useFakeTimers(); + } + } + globals.beforeEach(() => { + if (config.resetModules) { + runtime.resetModules(); + } + if (config.clearMocks) { + runtime.clearAllMocks(); + } + if (config.resetMocks) { + runtime.resetAllMocks(); + if ( + config.fakeTimers.enableGlobally && + config.fakeTimers.legacyFakeTimers + ) { + // during setup, this cannot be null (and it's fine to explode if it is) + environment.fakeTimers.useFakeTimers(); + } + } + if (config.restoreMocks) { + runtime.restoreAllMocks(); + } + }); + for (const path of config.setupFilesAfterEnv) { + const esm = runtime.unstable_shouldLoadAsEsm(path); + if (esm) { + await runtime.unstable_importModule(path); + } else { + runtime.requireModule(path); + } + } + const esm = runtime.unstable_shouldLoadAsEsm(testPath); + if (esm) { + await runtime.unstable_importModule(testPath); + } else { + runtime.requireModule(testPath); + } + const results = await runAndTransformResultsToJestFormat({ + config, + globalConfig, + testPath + }); + _addSnapshotData(results, snapshotState); + + // We need to copy the results object to ensure we don't leaks the prototypes + // from the VM. Jasmine creates the result objects in the parent process, we + // should consider doing that for circus as well. + return (0, _jestUtil.deepCyclicCopy)(results, { + keepPrototype: false + }); +}; +const _addSnapshotData = (results, snapshotState) => { + results.testResults.forEach(({fullName, status}) => { + if (status === 'pending' || status === 'failed') { + // if test is skipped or failed, we don't want to mark + // its snapshots as obsolete. + snapshotState.markSnapshotsAsCheckedForTest(fullName); + } + }); + const uncheckedCount = snapshotState.getUncheckedCount(); + const uncheckedKeys = snapshotState.getUncheckedKeys(); + if (uncheckedCount) { + snapshotState.removeUncheckedKeys(); + } + const status = snapshotState.save(); + results.snapshot.fileDeleted = status.deleted; + results.snapshot.added = snapshotState.added; + results.snapshot.matched = snapshotState.matched; + results.snapshot.unmatched = snapshotState.unmatched; + results.snapshot.updated = snapshotState.updated; + results.snapshot.unchecked = !status.deleted ? uncheckedCount : 0; + // Copy the array to prevent memory leaks + results.snapshot.uncheckedKeys = Array.from(uncheckedKeys); +}; +var _default = jestAdapter; +exports.default = _default; diff --git a/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js b/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js new file mode 100644 index 0000000..5d42e72 --- /dev/null +++ b/node_modules/jest-circus/build/legacy-code-todo-rewrite/jestAdapterInit.js @@ -0,0 +1,236 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.runAndTransformResultsToJestFormat = exports.initialize = void 0; +var _expect = require('@jest/expect'); +var _testResult = require('@jest/test-result'); +var _jestMessageUtil = require('jest-message-util'); +var _jestSnapshot = require('jest-snapshot'); +var _ = _interopRequireDefault(require('..')); +var _run = _interopRequireDefault(require('../run')); +var _state = require('../state'); +var _testCaseReportHandler = _interopRequireDefault( + require('../testCaseReportHandler') +); +var _utils = require('../utils'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const initialize = async ({ + config, + environment, + globalConfig, + localRequire, + parentProcess, + sendMessageToJest, + setGlobalsForRuntime, + testPath +}) => { + if (globalConfig.testTimeout) { + (0, _state.getState)().testTimeout = globalConfig.testTimeout; + } + (0, _state.getState)().maxConcurrency = globalConfig.maxConcurrency; + + // @ts-expect-error: missing `concurrent` which is added later + const globalsObject = { + ..._.default, + fdescribe: _.default.describe.only, + fit: _.default.it.only, + xdescribe: _.default.describe.skip, + xit: _.default.it.skip, + xtest: _.default.it.skip + }; + (0, _state.addEventHandler)(eventHandler); + if (environment.handleTestEvent) { + (0, _state.addEventHandler)(environment.handleTestEvent.bind(environment)); + } + _expect.jestExpect.setState({ + expand: globalConfig.expand + }); + const runtimeGlobals = { + ...globalsObject, + expect: _expect.jestExpect + }; + setGlobalsForRuntime(runtimeGlobals); + if (config.injectGlobals) { + Object.assign(environment.global, runtimeGlobals); + } + await (0, _state.dispatch)({ + name: 'setup', + parentProcess, + runtimeGlobals, + testNamePattern: globalConfig.testNamePattern + }); + if (config.testLocationInResults) { + await (0, _state.dispatch)({ + name: 'include_test_location_in_result' + }); + } + + // Jest tests snapshotSerializers in order preceding built-in serializers. + // Therefore, add in reverse because the last added is the first tested. + config.snapshotSerializers + .concat() + .reverse() + .forEach(path => (0, _jestSnapshot.addSerializer)(localRequire(path))); + const snapshotResolver = await (0, _jestSnapshot.buildSnapshotResolver)( + config, + localRequire + ); + const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath); + const snapshotState = new _jestSnapshot.SnapshotState(snapshotPath, { + expand: globalConfig.expand, + prettierPath: config.prettierPath, + rootDir: config.rootDir, + snapshotFormat: config.snapshotFormat, + updateSnapshot: globalConfig.updateSnapshot + }); + _expect.jestExpect.setState({ + snapshotState, + testPath + }); + (0, _state.addEventHandler)(handleSnapshotStateAfterRetry(snapshotState)); + if (sendMessageToJest) { + (0, _state.addEventHandler)( + (0, _testCaseReportHandler.default)(testPath, sendMessageToJest) + ); + } + + // Return it back to the outer scope (test runner outside the VM). + return { + globals: globalsObject, + snapshotState + }; +}; +exports.initialize = initialize; +const runAndTransformResultsToJestFormat = async ({ + config, + globalConfig, + testPath +}) => { + const runResult = await (0, _run.default)(); + let numFailingTests = 0; + let numPassingTests = 0; + let numPendingTests = 0; + let numTodoTests = 0; + const assertionResults = runResult.testResults.map(testResult => { + let status; + if (testResult.status === 'skip') { + status = 'pending'; + numPendingTests += 1; + } else if (testResult.status === 'todo') { + status = 'todo'; + numTodoTests += 1; + } else if (testResult.errors.length) { + status = 'failed'; + numFailingTests += 1; + } else { + status = 'passed'; + numPassingTests += 1; + } + const ancestorTitles = testResult.testPath.filter( + name => name !== _state.ROOT_DESCRIBE_BLOCK_NAME + ); + const title = ancestorTitles.pop(); + return { + ancestorTitles, + duration: testResult.duration, + failureDetails: testResult.errorsDetailed, + failureMessages: testResult.errors, + fullName: title + ? ancestorTitles.concat(title).join(' ') + : ancestorTitles.join(' '), + invocations: testResult.invocations, + location: testResult.location, + numPassingAsserts: 0, + retryReasons: testResult.retryReasons, + status, + title: testResult.testPath[testResult.testPath.length - 1] + }; + }); + let failureMessage = (0, _jestMessageUtil.formatResultsErrors)( + assertionResults, + config, + globalConfig, + testPath + ); + let testExecError; + if (runResult.unhandledErrors.length) { + testExecError = { + message: '', + stack: runResult.unhandledErrors.join('\n') + }; + failureMessage = `${failureMessage || ''}\n\n${runResult.unhandledErrors + .map(err => + (0, _jestMessageUtil.formatExecError)(err, config, globalConfig) + ) + .join('\n')}`; + } + await (0, _state.dispatch)({ + name: 'teardown' + }); + return { + ...(0, _testResult.createEmptyTestResult)(), + console: undefined, + displayName: config.displayName, + failureMessage, + numFailingTests, + numPassingTests, + numPendingTests, + numTodoTests, + testExecError, + testFilePath: testPath, + testResults: assertionResults + }; +}; +exports.runAndTransformResultsToJestFormat = runAndTransformResultsToJestFormat; +const handleSnapshotStateAfterRetry = snapshotState => event => { + switch (event.name) { + case 'test_retry': { + // Clear any snapshot data that occurred in previous test run + snapshotState.clear(); + } + } +}; +const eventHandler = async event => { + switch (event.name) { + case 'test_start': { + _expect.jestExpect.setState({ + currentTestName: (0, _utils.getTestID)(event.test) + }); + break; + } + case 'test_done': { + _addSuppressedErrors(event.test); + _addExpectedAssertionErrors(event.test); + break; + } + } +}; +const _addExpectedAssertionErrors = test => { + const failures = _expect.jestExpect.extractExpectedAssertionsErrors(); + const errors = failures.map(failure => failure.error); + test.errors = test.errors.concat(errors); +}; + +// Get suppressed errors from ``jest-matchers`` that weren't throw during +// test execution and add them to the test result, potentially failing +// a passing test. +const _addSuppressedErrors = test => { + const {suppressedErrors} = _expect.jestExpect.getState(); + _expect.jestExpect.setState({ + suppressedErrors: [] + }); + if (suppressedErrors.length) { + test.errors = test.errors.concat(suppressedErrors); + } +}; diff --git a/node_modules/jest-circus/build/run.js b/node_modules/jest-circus/build/run.js new file mode 100644 index 0000000..e68f12a --- /dev/null +++ b/node_modules/jest-circus/build/run.js @@ -0,0 +1,282 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _pLimit = _interopRequireDefault(require('p-limit')); +var _state = require('./state'); +var _types = require('./types'); +var _utils = require('./utils'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const run = async () => { + const {rootDescribeBlock} = (0, _state.getState)(); + await (0, _state.dispatch)({ + name: 'run_start' + }); + await _runTestsForDescribeBlock(rootDescribeBlock, true); + await (0, _state.dispatch)({ + name: 'run_finish' + }); + return (0, _utils.makeRunResult)( + (0, _state.getState)().rootDescribeBlock, + (0, _state.getState)().unhandledErrors + ); +}; +const _runTestsForDescribeBlock = async ( + describeBlock, + isRootBlock = false +) => { + await (0, _state.dispatch)({ + describeBlock, + name: 'run_describe_start' + }); + const {beforeAll, afterAll} = (0, _utils.getAllHooksForDescribe)( + describeBlock + ); + const isSkipped = describeBlock.mode === 'skip'; + if (!isSkipped) { + for (const hook of beforeAll) { + await _callCircusHook({ + describeBlock, + hook + }); + } + } + if (isRootBlock) { + const concurrentTests = collectConcurrentTests(describeBlock); + const mutex = (0, _pLimit.default)((0, _state.getState)().maxConcurrency); + for (const test of concurrentTests) { + try { + const promise = mutex(test.fn); + // Avoid triggering the uncaught promise rejection handler in case the + // test errors before being awaited on. + // eslint-disable-next-line @typescript-eslint/no-empty-function + promise.catch(() => {}); + test.fn = () => promise; + } catch (err) { + test.fn = () => { + throw err; + }; + } + } + } + + // Tests that fail and are retried we run after other tests + // eslint-disable-next-line no-restricted-globals + const retryTimes = parseInt(global[_types.RETRY_TIMES], 10) || 0; + const deferredRetryTests = []; + for (const child of describeBlock.children) { + switch (child.type) { + case 'describeBlock': { + await _runTestsForDescribeBlock(child); + break; + } + case 'test': { + const hasErrorsBeforeTestRun = child.errors.length > 0; + await _runTest(child, isSkipped); + if ( + hasErrorsBeforeTestRun === false && + retryTimes > 0 && + child.errors.length > 0 + ) { + deferredRetryTests.push(child); + } + break; + } + } + } + + // Re-run failed tests n-times if configured + for (const test of deferredRetryTests) { + let numRetriesAvailable = retryTimes; + while (numRetriesAvailable > 0 && test.errors.length > 0) { + // Clear errors so retries occur + await (0, _state.dispatch)({ + name: 'test_retry', + test + }); + await _runTest(test, isSkipped); + numRetriesAvailable--; + } + } + if (!isSkipped) { + for (const hook of afterAll) { + await _callCircusHook({ + describeBlock, + hook + }); + } + } + await (0, _state.dispatch)({ + describeBlock, + name: 'run_describe_finish' + }); +}; +function collectConcurrentTests(describeBlock) { + if (describeBlock.mode === 'skip') { + return []; + } + const {hasFocusedTests, testNamePattern} = (0, _state.getState)(); + return describeBlock.children.flatMap(child => { + switch (child.type) { + case 'describeBlock': + return collectConcurrentTests(child); + case 'test': + const skip = + !child.concurrent || + child.mode === 'skip' || + (hasFocusedTests && child.mode !== 'only') || + (testNamePattern && + !testNamePattern.test((0, _utils.getTestID)(child))); + return skip ? [] : [child]; + } + }); +} +const _runTest = async (test, parentSkipped) => { + await (0, _state.dispatch)({ + name: 'test_start', + test + }); + const testContext = Object.create(null); + const {hasFocusedTests, testNamePattern} = (0, _state.getState)(); + const isSkipped = + parentSkipped || + test.mode === 'skip' || + (hasFocusedTests && test.mode === undefined) || + (testNamePattern && !testNamePattern.test((0, _utils.getTestID)(test))); + if (isSkipped) { + await (0, _state.dispatch)({ + name: 'test_skip', + test + }); + return; + } + if (test.mode === 'todo') { + await (0, _state.dispatch)({ + name: 'test_todo', + test + }); + return; + } + const {afterEach, beforeEach} = (0, _utils.getEachHooksForTest)(test); + for (const hook of beforeEach) { + if (test.errors.length) { + // If any of the before hooks failed already, we don't run any + // hooks after that. + break; + } + await _callCircusHook({ + hook, + test, + testContext + }); + } + await _callCircusTest(test, testContext); + for (const hook of afterEach) { + await _callCircusHook({ + hook, + test, + testContext + }); + } + + // `afterAll` hooks should not affect test status (pass or fail), because if + // we had a global `afterAll` hook it would block all existing tests until + // this hook is executed. So we dispatch `test_done` right away. + await (0, _state.dispatch)({ + name: 'test_done', + test + }); +}; +const _callCircusHook = async ({ + hook, + test, + describeBlock, + testContext = {} +}) => { + await (0, _state.dispatch)({ + hook, + name: 'hook_start' + }); + const timeout = hook.timeout || (0, _state.getState)().testTimeout; + try { + await (0, _utils.callAsyncCircusFn)(hook, testContext, { + isHook: true, + timeout + }); + await (0, _state.dispatch)({ + describeBlock, + hook, + name: 'hook_success', + test + }); + } catch (error) { + await (0, _state.dispatch)({ + describeBlock, + error, + hook, + name: 'hook_failure', + test + }); + } +}; +const _callCircusTest = async (test, testContext) => { + await (0, _state.dispatch)({ + name: 'test_fn_start', + test + }); + const timeout = test.timeout || (0, _state.getState)().testTimeout; + (0, _utils.invariant)( + test.fn, + "Tests with no 'fn' should have 'mode' set to 'skipped'" + ); + if (test.errors.length) { + return; // We don't run the test if there's already an error in before hooks. + } + + try { + await (0, _utils.callAsyncCircusFn)(test, testContext, { + isHook: false, + timeout + }); + if (test.failing) { + test.asyncError.message = + 'Failing test passed even though it was supposed to fail. Remove `.failing` to remove error.'; + await (0, _state.dispatch)({ + error: test.asyncError, + name: 'test_fn_failure', + test + }); + } else { + await (0, _state.dispatch)({ + name: 'test_fn_success', + test + }); + } + } catch (error) { + if (test.failing) { + await (0, _state.dispatch)({ + name: 'test_fn_success', + test + }); + } else { + await (0, _state.dispatch)({ + error, + name: 'test_fn_failure', + test + }); + } + } +}; +var _default = run; +exports.default = _default; diff --git a/node_modules/jest-circus/build/state.js b/node_modules/jest-circus/build/state.js new file mode 100644 index 0000000..d98a639 --- /dev/null +++ b/node_modules/jest-circus/build/state.js @@ -0,0 +1,79 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.setState = + exports.resetState = + exports.getState = + exports.dispatchSync = + exports.dispatch = + exports.addEventHandler = + exports.ROOT_DESCRIBE_BLOCK_NAME = + void 0; +var _eventHandler = _interopRequireDefault(require('./eventHandler')); +var _formatNodeAssertErrors = _interopRequireDefault( + require('./formatNodeAssertErrors') +); +var _types = require('./types'); +var _utils = require('./utils'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const eventHandlers = [_eventHandler.default, _formatNodeAssertErrors.default]; +const ROOT_DESCRIBE_BLOCK_NAME = 'ROOT_DESCRIBE_BLOCK'; +exports.ROOT_DESCRIBE_BLOCK_NAME = ROOT_DESCRIBE_BLOCK_NAME; +const createState = () => { + const ROOT_DESCRIBE_BLOCK = (0, _utils.makeDescribe)( + ROOT_DESCRIBE_BLOCK_NAME + ); + return { + currentDescribeBlock: ROOT_DESCRIBE_BLOCK, + currentlyRunningTest: null, + expand: undefined, + hasFocusedTests: false, + hasStarted: false, + includeTestLocationInResult: false, + maxConcurrency: 5, + parentProcess: null, + rootDescribeBlock: ROOT_DESCRIBE_BLOCK, + testNamePattern: null, + testTimeout: 5000, + unhandledErrors: [] + }; +}; + +/* eslint-disable no-restricted-globals */ +const resetState = () => { + global[_types.STATE_SYM] = createState(); +}; +exports.resetState = resetState; +resetState(); +const getState = () => global[_types.STATE_SYM]; +exports.getState = getState; +const setState = state => (global[_types.STATE_SYM] = state); +/* eslint-enable */ +exports.setState = setState; +const dispatch = async event => { + for (const handler of eventHandlers) { + await handler(event, getState()); + } +}; +exports.dispatch = dispatch; +const dispatchSync = event => { + for (const handler of eventHandlers) { + handler(event, getState()); + } +}; +exports.dispatchSync = dispatchSync; +const addEventHandler = handler => { + eventHandlers.push(handler); +}; +exports.addEventHandler = addEventHandler; diff --git a/node_modules/jest-circus/build/testCaseReportHandler.js b/node_modules/jest-circus/build/testCaseReportHandler.js new file mode 100644 index 0000000..24f0b3d --- /dev/null +++ b/node_modules/jest-circus/build/testCaseReportHandler.js @@ -0,0 +1,26 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _utils = require('./utils'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const testCaseReportHandler = (testPath, sendMessageToJest) => event => { + switch (event.name) { + case 'test_done': { + const testResult = (0, _utils.makeSingleTestResult)(event.test); + const testCaseResult = (0, _utils.parseSingleTestResult)(testResult); + sendMessageToJest('test-case-result', [testPath, testCaseResult]); + break; + } + } +}; +var _default = testCaseReportHandler; +exports.default = _default; diff --git a/node_modules/jest-circus/build/types.js b/node_modules/jest-circus/build/types.js new file mode 100644 index 0000000..d351ca2 --- /dev/null +++ b/node_modules/jest-circus/build/types.js @@ -0,0 +1,27 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.TEST_TIMEOUT_SYMBOL = + exports.STATE_SYM = + exports.RETRY_TIMES = + exports.LOG_ERRORS_BEFORE_RETRY = + void 0; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const STATE_SYM = Symbol('JEST_STATE_SYMBOL'); +exports.STATE_SYM = STATE_SYM; +const RETRY_TIMES = Symbol.for('RETRY_TIMES'); +// To pass this value from Runtime object to state we need to use global[sym] +exports.RETRY_TIMES = RETRY_TIMES; +const TEST_TIMEOUT_SYMBOL = Symbol.for('TEST_TIMEOUT_SYMBOL'); +exports.TEST_TIMEOUT_SYMBOL = TEST_TIMEOUT_SYMBOL; +const LOG_ERRORS_BEFORE_RETRY = Symbol.for('LOG_ERRORS_BEFORE_RETRY'); +exports.LOG_ERRORS_BEFORE_RETRY = LOG_ERRORS_BEFORE_RETRY; diff --git a/node_modules/jest-circus/build/utils.js b/node_modules/jest-circus/build/utils.js new file mode 100644 index 0000000..3c7beba --- /dev/null +++ b/node_modules/jest-circus/build/utils.js @@ -0,0 +1,480 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getTestID = + exports.getTestDuration = + exports.getEachHooksForTest = + exports.getAllHooksForDescribe = + exports.describeBlockHasTests = + exports.callAsyncCircusFn = + exports.addErrorToEachTestUnderDescribe = + void 0; +exports.invariant = invariant; +exports.parseSingleTestResult = + exports.makeTest = + exports.makeSingleTestResult = + exports.makeRunResult = + exports.makeDescribe = + void 0; +var path = _interopRequireWildcard(require('path')); +var _co = _interopRequireDefault(require('co')); +var _dedent = _interopRequireDefault(require('dedent')); +var _isGeneratorFn = _interopRequireDefault(require('is-generator-fn')); +var _slash = _interopRequireDefault(require('slash')); +var _stackUtils = _interopRequireDefault(require('stack-utils')); +var _jestUtil = require('jest-util'); +var _prettyFormat = require('pretty-format'); +var _state = require('./state'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestNow = globalThis[Symbol.for('jest-native-now')] || globalThis.Date.now; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Promise = + globalThis[Symbol.for('jest-native-promise')] || globalThis.Promise; +const stackUtils = new _stackUtils.default({ + cwd: 'A path that does not exist' +}); +const jestEachBuildDir = (0, _slash.default)( + path.dirname(require.resolve('jest-each')) +); +function takesDoneCallback(fn) { + return fn.length > 0; +} +function isGeneratorFunction(fn) { + return (0, _isGeneratorFn.default)(fn); +} +const makeDescribe = (name, parent, mode) => { + let _mode = mode; + if (parent && !mode) { + // If not set explicitly, inherit from the parent describe. + _mode = parent.mode; + } + return { + type: 'describeBlock', + // eslint-disable-next-line sort-keys + children: [], + hooks: [], + mode: _mode, + name: (0, _jestUtil.convertDescriptorToString)(name), + parent, + tests: [] + }; +}; +exports.makeDescribe = makeDescribe; +const makeTest = ( + fn, + mode, + concurrent, + name, + parent, + timeout, + asyncError, + failing +) => ({ + type: 'test', + // eslint-disable-next-line sort-keys + asyncError, + concurrent, + duration: null, + errors: [], + failing, + fn, + invocations: 0, + mode, + name: (0, _jestUtil.convertDescriptorToString)(name), + parent, + retryReasons: [], + seenDone: false, + startedAt: null, + status: null, + timeout +}); + +// Traverse the tree of describe blocks and return true if at least one describe +// block has an enabled test. +exports.makeTest = makeTest; +const hasEnabledTest = describeBlock => { + const {hasFocusedTests, testNamePattern} = (0, _state.getState)(); + return describeBlock.children.some(child => + child.type === 'describeBlock' + ? hasEnabledTest(child) + : !( + child.mode === 'skip' || + (hasFocusedTests && child.mode !== 'only') || + (testNamePattern && !testNamePattern.test(getTestID(child))) + ) + ); +}; +const getAllHooksForDescribe = describe => { + const result = { + afterAll: [], + beforeAll: [] + }; + if (hasEnabledTest(describe)) { + for (const hook of describe.hooks) { + switch (hook.type) { + case 'beforeAll': + result.beforeAll.push(hook); + break; + case 'afterAll': + result.afterAll.push(hook); + break; + } + } + } + return result; +}; +exports.getAllHooksForDescribe = getAllHooksForDescribe; +const getEachHooksForTest = test => { + const result = { + afterEach: [], + beforeEach: [] + }; + if (test.concurrent) { + // *Each hooks are not run for concurrent tests + return result; + } + let block = test.parent; + do { + const beforeEachForCurrentBlock = []; + for (const hook of block.hooks) { + switch (hook.type) { + case 'beforeEach': + beforeEachForCurrentBlock.push(hook); + break; + case 'afterEach': + result.afterEach.push(hook); + break; + } + } + // 'beforeEach' hooks are executed from top to bottom, the opposite of the + // way we traversed it. + result.beforeEach = [...beforeEachForCurrentBlock, ...result.beforeEach]; + } while ((block = block.parent)); + return result; +}; +exports.getEachHooksForTest = getEachHooksForTest; +const describeBlockHasTests = describe => + describe.children.some( + child => child.type === 'test' || describeBlockHasTests(child) + ); +exports.describeBlockHasTests = describeBlockHasTests; +const _makeTimeoutMessage = (timeout, isHook) => + `Exceeded timeout of ${(0, _jestUtil.formatTime)(timeout)} for a ${ + isHook ? 'hook' : 'test' + }.\nUse jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.`; + +// Global values can be overwritten by mocks or tests. We'll capture +// the original values in the variables before we require any files. +const {setTimeout, clearTimeout} = globalThis; +function checkIsError(error) { + return !!(error && error.message && error.stack); +} +const callAsyncCircusFn = (testOrHook, testContext, {isHook, timeout}) => { + let timeoutID; + let completed = false; + const {fn, asyncError} = testOrHook; + return new Promise((resolve, reject) => { + timeoutID = setTimeout( + () => reject(_makeTimeoutMessage(timeout, isHook)), + timeout + ); + + // If this fn accepts `done` callback we return a promise that fulfills as + // soon as `done` called. + if (takesDoneCallback(fn)) { + let returnedValue = undefined; + const done = reason => { + // We need to keep a stack here before the promise tick + const errorAtDone = new _jestUtil.ErrorWithStack(undefined, done); + if (!completed && testOrHook.seenDone) { + errorAtDone.message = + 'Expected done to be called once, but it was called multiple times.'; + if (reason) { + errorAtDone.message += ` Reason: ${(0, _prettyFormat.format)( + reason, + { + maxDepth: 3 + } + )}`; + } + reject(errorAtDone); + throw errorAtDone; + } else { + testOrHook.seenDone = true; + } + + // Use `Promise.resolve` to allow the event loop to go a single tick in case `done` is called synchronously + Promise.resolve().then(() => { + if (returnedValue !== undefined) { + asyncError.message = (0, _dedent.default)` + Test functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise. + Returned value: ${(0, _prettyFormat.format)(returnedValue, { + maxDepth: 3 + })} + `; + return reject(asyncError); + } + let errorAsErrorObject; + if (checkIsError(reason)) { + errorAsErrorObject = reason; + } else { + errorAsErrorObject = errorAtDone; + errorAtDone.message = `Failed: ${(0, _prettyFormat.format)(reason, { + maxDepth: 3 + })}`; + } + + // Consider always throwing, regardless if `reason` is set or not + if (completed && reason) { + errorAsErrorObject.message = `Caught error after test environment was torn down\n\n${errorAsErrorObject.message}`; + throw errorAsErrorObject; + } + return reason ? reject(errorAsErrorObject) : resolve(); + }); + }; + returnedValue = fn.call(testContext, done); + return; + } + let returnedValue; + if (isGeneratorFunction(fn)) { + returnedValue = _co.default.wrap(fn).call({}); + } else { + try { + returnedValue = fn.call(testContext); + } catch (error) { + reject(error); + return; + } + } + if ((0, _jestUtil.isPromise)(returnedValue)) { + returnedValue.then(() => resolve(), reject); + return; + } + if (!isHook && returnedValue !== undefined) { + reject( + new Error((0, _dedent.default)` + test functions can only return Promise or undefined. + Returned value: ${(0, _prettyFormat.format)(returnedValue, { + maxDepth: 3 + })} + `) + ); + return; + } + + // Otherwise this test is synchronous, and if it didn't throw it means + // it passed. + resolve(); + }) + .then(() => { + completed = true; + // If timeout is not cleared/unrefed the node process won't exit until + // it's resolved. + timeoutID.unref?.(); + clearTimeout(timeoutID); + }) + .catch(error => { + completed = true; + timeoutID.unref?.(); + clearTimeout(timeoutID); + throw error; + }); +}; +exports.callAsyncCircusFn = callAsyncCircusFn; +const getTestDuration = test => { + const {startedAt} = test; + return typeof startedAt === 'number' ? jestNow() - startedAt : null; +}; +exports.getTestDuration = getTestDuration; +const makeRunResult = (describeBlock, unhandledErrors) => ({ + testResults: makeTestResults(describeBlock), + unhandledErrors: unhandledErrors.map(_getError).map(getErrorStack) +}); +exports.makeRunResult = makeRunResult; +const makeSingleTestResult = test => { + const {includeTestLocationInResult} = (0, _state.getState)(); + const testPath = []; + let parent = test; + const {status} = test; + invariant(status, 'Status should be present after tests are run.'); + do { + testPath.unshift(parent.name); + } while ((parent = parent.parent)); + let location = null; + if (includeTestLocationInResult) { + const stackLines = test.asyncError.stack.split('\n'); + const stackLine = stackLines[1]; + let parsedLine = stackUtils.parseLine(stackLine); + if (parsedLine?.file?.startsWith(jestEachBuildDir)) { + const stackLine = stackLines[4]; + parsedLine = stackUtils.parseLine(stackLine); + } + if ( + parsedLine && + typeof parsedLine.column === 'number' && + typeof parsedLine.line === 'number' + ) { + location = { + column: parsedLine.column, + line: parsedLine.line + }; + } + } + const errorsDetailed = test.errors.map(_getError); + return { + duration: test.duration, + errors: errorsDetailed.map(getErrorStack), + errorsDetailed, + invocations: test.invocations, + location, + retryReasons: test.retryReasons.map(_getError).map(getErrorStack), + status, + testPath: Array.from(testPath) + }; +}; +exports.makeSingleTestResult = makeSingleTestResult; +const makeTestResults = describeBlock => { + const testResults = []; + for (const child of describeBlock.children) { + switch (child.type) { + case 'describeBlock': { + testResults.push(...makeTestResults(child)); + break; + } + case 'test': { + testResults.push(makeSingleTestResult(child)); + break; + } + } + } + return testResults; +}; + +// Return a string that identifies the test (concat of parent describe block +// names + test title) +const getTestID = test => { + const titles = []; + let parent = test; + do { + titles.unshift(parent.name); + } while ((parent = parent.parent)); + titles.shift(); // remove TOP_DESCRIBE_BLOCK_NAME + return titles.join(' '); +}; +exports.getTestID = getTestID; +const _getError = errors => { + let error; + let asyncError; + if (Array.isArray(errors)) { + error = errors[0]; + asyncError = errors[1]; + } else { + error = errors; + asyncError = new Error(); + } + if (error && (typeof error.stack === 'string' || error.message)) { + return error; + } + asyncError.message = `thrown: ${(0, _prettyFormat.format)(error, { + maxDepth: 3 + })}`; + return asyncError; +}; +const getErrorStack = error => + typeof error.stack === 'string' ? error.stack : error.message; +const addErrorToEachTestUnderDescribe = (describeBlock, error, asyncError) => { + for (const child of describeBlock.children) { + switch (child.type) { + case 'describeBlock': + addErrorToEachTestUnderDescribe(child, error, asyncError); + break; + case 'test': + child.errors.push([error, asyncError]); + break; + } + } +}; +exports.addErrorToEachTestUnderDescribe = addErrorToEachTestUnderDescribe; +function invariant(condition, message) { + if (!condition) { + throw new Error(message); + } +} +const parseSingleTestResult = testResult => { + let status; + if (testResult.status === 'skip') { + status = 'pending'; + } else if (testResult.status === 'todo') { + status = 'todo'; + } else if (testResult.errors.length > 0) { + status = 'failed'; + } else { + status = 'passed'; + } + const ancestorTitles = testResult.testPath.filter( + name => name !== _state.ROOT_DESCRIBE_BLOCK_NAME + ); + const title = ancestorTitles.pop(); + return { + ancestorTitles, + duration: testResult.duration, + failureDetails: testResult.errorsDetailed, + failureMessages: Array.from(testResult.errors), + fullName: title + ? ancestorTitles.concat(title).join(' ') + : ancestorTitles.join(' '), + invocations: testResult.invocations, + location: testResult.location, + numPassingAsserts: 0, + retryReasons: Array.from(testResult.retryReasons), + status, + title: testResult.testPath[testResult.testPath.length - 1] + }; +}; +exports.parseSingleTestResult = parseSingleTestResult; diff --git a/node_modules/jest-circus/package.json b/node_modules/jest-circus/package.json new file mode 100644 index 0000000..e724c78 --- /dev/null +++ b/node_modules/jest-circus/package.json @@ -0,0 +1,58 @@ +{ + "name": "jest-circus", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-circus" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json", + "./runner": "./runner.js" + }, + "dependencies": { + "@jest/environment": "^29.2.2", + "@jest/expect": "^29.2.2", + "@jest/test-result": "^29.2.1", + "@jest/types": "^29.2.1", + "@types/node": "*", + "chalk": "^4.0.0", + "co": "^4.6.0", + "dedent": "^0.7.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^29.2.1", + "jest-matcher-utils": "^29.2.2", + "jest-message-util": "^29.2.1", + "jest-runtime": "^29.2.2", + "jest-snapshot": "^29.2.2", + "jest-util": "^29.2.1", + "p-limit": "^3.1.0", + "pretty-format": "^29.2.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "devDependencies": { + "@babel/core": "^7.11.6", + "@babel/register": "^7.0.0", + "@types/co": "^4.6.2", + "@types/dedent": "^0.7.0", + "@types/graceful-fs": "^4.1.3", + "@types/stack-utils": "^2.0.0", + "execa": "^5.0.0", + "graceful-fs": "^4.2.9" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-circus/runner.js b/node_modules/jest-circus/runner.js new file mode 100644 index 0000000..f61fd88 --- /dev/null +++ b/node_modules/jest-circus/runner.js @@ -0,0 +1,10 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Allow people to use `jest-circus/runner` as a runner. +const runner = require('./build/legacy-code-todo-rewrite/jestAdapter').default; +module.exports = runner; diff --git a/node_modules/jest-cli/LICENSE b/node_modules/jest-cli/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-cli/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-cli/README.md b/node_modules/jest-cli/README.md new file mode 100644 index 0000000..9c3d31e --- /dev/null +++ b/node_modules/jest-cli/README.md @@ -0,0 +1,11 @@ +# Jest + +🃏 Delightful JavaScript Testing + +- **👩🏻‍💻 Developer Ready**: Complete and ready to set-up JavaScript testing solution. Works out of the box for any React project. + +- **🏃🏽 Instant Feedback**: Failed tests run first. Fast interactive mode can switch between running all tests or only test files related to changed files. + +- **📸 Snapshot Testing**: Jest can [capture snapshots](https://jestjs.io/docs/snapshot-testing) of React trees or other serializable values to simplify UI testing. + +Read More: https://jestjs.io/ diff --git a/node_modules/jest-cli/bin/jest.js b/node_modules/jest-cli/bin/jest.js new file mode 100644 index 0000000..146fb2c --- /dev/null +++ b/node_modules/jest-cli/bin/jest.js @@ -0,0 +1,17 @@ +#!/usr/bin/env node +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const importLocal = require('import-local'); + +if (!importLocal(__filename)) { + if (process.env.NODE_ENV == null) { + process.env.NODE_ENV = 'test'; + } + + require('..').run(); +} diff --git a/node_modules/jest-cli/build/args.js b/node_modules/jest-cli/build/args.js new file mode 100644 index 0000000..ddbb368 --- /dev/null +++ b/node_modules/jest-cli/build/args.js @@ -0,0 +1,716 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.check = check; +exports.usage = exports.options = exports.docs = void 0; +function _jestConfig() { + const data = require('jest-config'); + _jestConfig = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function check(argv) { + if ( + argv.runInBand && + Object.prototype.hasOwnProperty.call(argv, 'maxWorkers') + ) { + throw new Error( + 'Both --runInBand and --maxWorkers were specified, but these two ' + + 'options do not make sense together. Which is it?' + ); + } + for (const key of [ + 'onlyChanged', + 'lastCommit', + 'changedFilesWithAncestor', + 'changedSince' + ]) { + if (argv[key] && argv.watchAll) { + throw new Error( + `Both --${key} and --watchAll were specified, but these two ` + + 'options do not make sense together. Try the --watch option which ' + + 'reruns only tests related to changed files.' + ); + } + } + if (argv.onlyFailures && argv.watchAll) { + throw new Error( + 'Both --onlyFailures and --watchAll were specified, but these two ' + + 'options do not make sense together.' + ); + } + if (argv.findRelatedTests && argv._.length === 0) { + throw new Error( + 'The --findRelatedTests option requires file paths to be specified.\n' + + 'Example usage: jest --findRelatedTests ./src/source.js ' + + './src/index.js.' + ); + } + if ( + Object.prototype.hasOwnProperty.call(argv, 'maxWorkers') && + argv.maxWorkers === undefined + ) { + throw new Error( + 'The --maxWorkers (-w) option requires a number or string to be specified.\n' + + 'Example usage: jest --maxWorkers 2\n' + + 'Example usage: jest --maxWorkers 50%\n' + + 'Or did you mean --watch?' + ); + } + if (argv.selectProjects && argv.selectProjects.length === 0) { + throw new Error( + 'The --selectProjects option requires the name of at least one project to be specified.\n' + + 'Example usage: jest --selectProjects my-first-project my-second-project' + ); + } + if (argv.ignoreProjects && argv.ignoreProjects.length === 0) { + throw new Error( + 'The --ignoreProjects option requires the name of at least one project to be specified.\n' + + 'Example usage: jest --ignoreProjects my-first-project my-second-project' + ); + } + if ( + argv.config && + !(0, _jestConfig().isJSONString)(argv.config) && + !argv.config.match( + new RegExp( + `\\.(${_jestConfig() + .constants.JEST_CONFIG_EXT_ORDER.map(e => e.substring(1)) + .join('|')})$`, + 'i' + ) + ) + ) { + throw new Error( + `The --config option requires a JSON string literal, or a file path with one of these extensions: ${_jestConfig().constants.JEST_CONFIG_EXT_ORDER.join( + ', ' + )}.\nExample usage: jest --config ./jest.config.js` + ); + } + return true; +} +const usage = 'Usage: $0 [--config=] [TestPathPattern]'; +exports.usage = usage; +const docs = 'Documentation: https://jestjs.io/'; + +// The default values are all set in jest-config +exports.docs = docs; +const options = { + all: { + description: + 'The opposite of `onlyChanged`. If `onlyChanged` is set by ' + + 'default, running jest with `--all` will force Jest to run all tests ' + + 'instead of running only tests related to changed files.', + type: 'boolean' + }, + automock: { + description: 'Automock all files by default.', + type: 'boolean' + }, + bail: { + alias: 'b', + description: + 'Exit the test suite immediately after `n` number of failing tests.', + type: 'boolean' + }, + cache: { + description: + 'Whether to use the transform cache. Disable the cache ' + + 'using --no-cache.', + type: 'boolean' + }, + cacheDirectory: { + description: + 'The directory where Jest should store its cached ' + + ' dependency information.', + type: 'string' + }, + changedFilesWithAncestor: { + description: + 'Runs tests related to the current changes and the changes made in the ' + + 'last commit. Behaves similarly to `--onlyChanged`.', + type: 'boolean' + }, + changedSince: { + description: + 'Runs tests related to the changes since the provided branch. If the ' + + 'current branch has diverged from the given branch, then only changes ' + + 'made locally will be tested. Behaves similarly to `--onlyChanged`.', + nargs: 1, + type: 'string' + }, + ci: { + description: + 'Whether to run Jest in continuous integration (CI) mode. ' + + 'This option is on by default in most popular CI environments. It will ' + + 'prevent snapshots from being written unless explicitly requested.', + type: 'boolean' + }, + clearCache: { + description: + 'Clears the configured Jest cache directory and then exits. ' + + 'Default directory can be found by calling jest --showConfig', + type: 'boolean' + }, + clearMocks: { + description: + 'Automatically clear mock calls, instances, contexts and results before every test. ' + + 'Equivalent to calling jest.clearAllMocks() before each test.', + type: 'boolean' + }, + collectCoverage: { + description: 'Alias for --coverage.', + type: 'boolean' + }, + collectCoverageFrom: { + description: + 'A glob pattern relative to matching the files that coverage ' + + 'info needs to be collected from.', + type: 'string' + }, + color: { + description: + 'Forces test results output color highlighting (even if ' + + 'stdout is not a TTY). Set to false if you would like to have no colors.', + type: 'boolean' + }, + colors: { + description: 'Alias for `--color`.', + type: 'boolean' + }, + config: { + alias: 'c', + description: + 'The path to a jest config file specifying how to find ' + + 'and execute tests. If no rootDir is set in the config, the directory ' + + 'containing the config file is assumed to be the rootDir for the project. ' + + 'This can also be a JSON encoded value which Jest will use as configuration.', + type: 'string' + }, + coverage: { + description: + 'Indicates that test coverage information should be ' + + 'collected and reported in the output.', + type: 'boolean' + }, + coverageDirectory: { + description: 'The directory where Jest should output its coverage files.', + type: 'string' + }, + coveragePathIgnorePatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all file paths before executing the test. If the file path ' + + 'matches any of the patterns, coverage information will be skipped.', + string: true, + type: 'array' + }, + coverageProvider: { + choices: ['babel', 'v8'], + description: 'Select between Babel and V8 to collect coverage' + }, + coverageReporters: { + description: + 'A list of reporter names that Jest uses when writing ' + + 'coverage reports. Any istanbul reporter can be used.', + string: true, + type: 'array' + }, + coverageThreshold: { + description: + 'A JSON string with which will be used to configure ' + + 'minimum threshold enforcement for coverage results', + type: 'string' + }, + debug: { + description: 'Print debugging info about your jest config.', + type: 'boolean' + }, + detectLeaks: { + description: + '**EXPERIMENTAL**: Detect memory leaks in tests. After executing a ' + + 'test, it will try to garbage collect the global object used, and fail ' + + 'if it was leaked', + type: 'boolean' + }, + detectOpenHandles: { + description: + 'Print out remaining open handles preventing Jest from exiting at the ' + + 'end of a test run. Implies `runInBand`.', + type: 'boolean' + }, + env: { + description: + 'The test environment used for all tests. This can point to ' + + 'any file or node module. Examples: `jsdom`, `node` or ' + + '`path/to/my-environment.js`', + type: 'string' + }, + errorOnDeprecated: { + description: 'Make calling deprecated APIs throw helpful error messages.', + type: 'boolean' + }, + expand: { + alias: 'e', + description: 'Use this flag to show full diffs instead of a patch.', + type: 'boolean' + }, + filter: { + description: + 'Path to a module exporting a filtering function. This method receives ' + + 'a list of tests which can be manipulated to exclude tests from ' + + 'running. Especially useful when used in conjunction with a testing ' + + 'infrastructure to filter known broken tests.', + type: 'string' + }, + findRelatedTests: { + description: + 'Find related tests for a list of source files that were ' + + 'passed in as arguments. Useful for pre-commit hook integration to run ' + + 'the minimal amount of tests necessary.', + type: 'boolean' + }, + forceExit: { + description: + 'Force Jest to exit after all tests have completed running. ' + + 'This is useful when resources set up by test code cannot be ' + + 'adequately cleaned up.', + type: 'boolean' + }, + globalSetup: { + description: 'The path to a module that runs before All Tests.', + type: 'string' + }, + globalTeardown: { + description: 'The path to a module that runs after All Tests.', + type: 'string' + }, + globals: { + description: + 'A JSON string with map of global variables that need ' + + 'to be available in all test environments.', + type: 'string' + }, + haste: { + description: + 'A JSON string with map of variables for the haste module system', + type: 'string' + }, + ignoreProjects: { + description: + 'Ignore the tests of the specified projects. ' + + 'Jest uses the attribute `displayName` in the configuration to identify each project.', + string: true, + type: 'array' + }, + init: { + description: 'Generate a basic configuration file', + type: 'boolean' + }, + injectGlobals: { + description: 'Should Jest inject global variables or not', + type: 'boolean' + }, + json: { + description: + 'Prints the test results in JSON. This mode will send all ' + + 'other test output and user messages to stderr.', + type: 'boolean' + }, + lastCommit: { + description: + 'Run all tests affected by file changes in the last commit made. ' + + 'Behaves similarly to `--onlyChanged`.', + type: 'boolean' + }, + listTests: { + description: + 'Lists all tests Jest will run given the arguments and ' + + 'exits. Most useful in a CI system together with `--findRelatedTests` ' + + 'to determine the tests Jest will run based on specific files', + type: 'boolean' + }, + logHeapUsage: { + description: + 'Logs the heap usage after every test. Useful to debug ' + + 'memory leaks. Use together with `--runInBand` and `--expose-gc` in ' + + 'node.', + type: 'boolean' + }, + maxConcurrency: { + description: + 'Specifies the maximum number of tests that are allowed to run ' + + 'concurrently. This only affects tests using `test.concurrent`.', + type: 'number' + }, + maxWorkers: { + alias: 'w', + description: + 'Specifies the maximum number of workers the worker-pool ' + + 'will spawn for running tests. This defaults to the number of the ' + + 'cores available on your machine. (its usually best not to override ' + + 'this default)', + type: 'string' + }, + moduleDirectories: { + description: + 'An array of directory names to be searched recursively ' + + "up from the requiring module's location.", + string: true, + type: 'array' + }, + moduleFileExtensions: { + description: + 'An array of file extensions your modules use. If you ' + + 'require modules without specifying a file extension, these are the ' + + 'extensions Jest will look for.', + string: true, + type: 'array' + }, + moduleNameMapper: { + description: + 'A JSON string with a map from regular expressions to ' + + 'module names or to arrays of module names that allow to stub ' + + 'out resources, like images or styles with a single module', + type: 'string' + }, + modulePathIgnorePatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all module paths before those paths are to be considered ' + + '"visible" to the module loader.', + string: true, + type: 'array' + }, + modulePaths: { + description: + 'An alternative API to setting the NODE_PATH env variable, ' + + 'modulePaths is an array of absolute paths to additional locations to ' + + 'search when resolving modules.', + string: true, + type: 'array' + }, + noStackTrace: { + description: 'Disables stack trace in test results output', + type: 'boolean' + }, + notify: { + description: 'Activates notifications for test results.', + type: 'boolean' + }, + notifyMode: { + description: 'Specifies when notifications will appear for test results.', + type: 'string' + }, + onlyChanged: { + alias: 'o', + description: + 'Attempts to identify which tests to run based on which ' + + "files have changed in the current repository. Only works if you're " + + 'running tests in a git or hg repository at the moment.', + type: 'boolean' + }, + onlyFailures: { + alias: 'f', + description: 'Run tests that failed in the previous execution.', + type: 'boolean' + }, + outputFile: { + description: + 'Write test results to a file when the --json option is ' + + 'also specified.', + type: 'string' + }, + passWithNoTests: { + description: + 'Will not fail if no tests are found (for example while using `--testPathPattern`.)', + type: 'boolean' + }, + preset: { + description: "A preset that is used as a base for Jest's configuration.", + type: 'string' + }, + prettierPath: { + description: 'The path to the "prettier" module used for inline snapshots.', + type: 'string' + }, + projects: { + description: + 'A list of projects that use Jest to run all tests of all ' + + 'projects in a single instance of Jest.', + string: true, + type: 'array' + }, + reporters: { + description: 'A list of custom reporters for the test suite.', + string: true, + type: 'array' + }, + resetMocks: { + description: + 'Automatically reset mock state before every test. ' + + 'Equivalent to calling jest.resetAllMocks() before each test.', + type: 'boolean' + }, + resetModules: { + description: + 'If enabled, the module registry for every test file will ' + + 'be reset before running each individual test.', + type: 'boolean' + }, + resolver: { + description: 'A JSON string which allows the use of a custom resolver.', + type: 'string' + }, + restoreMocks: { + description: + 'Automatically restore mock state and implementation before every test. ' + + 'Equivalent to calling jest.restoreAllMocks() before each test.', + type: 'boolean' + }, + rootDir: { + description: + 'The root directory that Jest should scan for tests and ' + + 'modules within.', + type: 'string' + }, + roots: { + description: + 'A list of paths to directories that Jest should use to ' + + 'search for files in.', + string: true, + type: 'array' + }, + runInBand: { + alias: 'i', + description: + 'Run all tests serially in the current process (rather than ' + + 'creating a worker pool of child processes that run tests). This ' + + 'is sometimes useful for debugging, but such use cases are pretty ' + + 'rare.', + type: 'boolean' + }, + runTestsByPath: { + description: + 'Used when provided patterns are exact file paths. This avoids ' + + 'converting them into a regular expression and matching it against ' + + 'every single file.', + type: 'boolean' + }, + runner: { + description: + "Allows to use a custom runner instead of Jest's default test runner.", + type: 'string' + }, + seed: { + description: + 'Sets a seed value that can be retrieved in a tests file via `jest.getSeed()`. If this option is not specified Jest will randomly generate the value. The seed value must be between `-0x80000000` and `0x7fffffff` inclusive.', + type: 'number' + }, + selectProjects: { + description: + 'Run the tests of the specified projects. ' + + 'Jest uses the attribute `displayName` in the configuration to identify each project.', + string: true, + type: 'array' + }, + setupFiles: { + description: + 'A list of paths to modules that run some code to configure or ' + + 'set up the testing environment before each test.', + string: true, + type: 'array' + }, + setupFilesAfterEnv: { + description: + 'A list of paths to modules that run some code to configure or ' + + 'set up the testing framework before each test', + string: true, + type: 'array' + }, + shard: { + description: + 'Shard tests and execute only the selected shard, specify in ' + + 'the form "current/all". 1-based, for example "3/5".', + type: 'string' + }, + showConfig: { + description: 'Print your jest config and then exits.', + type: 'boolean' + }, + showSeed: { + description: + 'Prints the seed value in the test report summary. See `--seed` for how to set this value', + type: 'boolean' + }, + silent: { + description: 'Prevent tests from printing messages through the console.', + type: 'boolean' + }, + skipFilter: { + description: + 'Disables the filter provided by --filter. Useful for CI jobs, or ' + + 'local enforcement when fixing tests.', + type: 'boolean' + }, + snapshotSerializers: { + description: + 'A list of paths to snapshot serializer modules Jest should ' + + 'use for snapshot testing.', + string: true, + type: 'array' + }, + testEnvironment: { + description: 'Alias for --env', + type: 'string' + }, + testEnvironmentOptions: { + description: + 'A JSON string with options that will be passed to the `testEnvironment`. ' + + 'The relevant options depend on the environment.', + type: 'string' + }, + testFailureExitCode: { + description: 'Exit code of `jest` command if the test run failed', + type: 'string' // number + }, + + testLocationInResults: { + description: 'Add `location` information to the test results', + type: 'boolean' + }, + testMatch: { + description: 'The glob patterns Jest uses to detect test files.', + string: true, + type: 'array' + }, + testNamePattern: { + alias: 't', + description: 'Run only tests with a name that matches the regex pattern.', + type: 'string' + }, + testPathIgnorePatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all test paths before executing the test. If the test path ' + + 'matches any of the patterns, it will be skipped.', + string: true, + type: 'array' + }, + testPathPattern: { + description: + 'A regexp pattern string that is matched against all tests ' + + 'paths before executing the test.', + string: true, + type: 'array' + }, + testRegex: { + description: + 'A string or array of string regexp patterns that Jest uses to detect test files.', + string: true, + type: 'array' + }, + testResultsProcessor: { + description: + 'Allows the use of a custom results processor. ' + + 'This processor must be a node module that exports ' + + 'a function expecting as the first argument the result object.', + type: 'string' + }, + testRunner: { + description: + 'Allows to specify a custom test runner. The default is' + + ' `jest-circus/runner`. A path to a custom test runner can be provided:' + + ' `/path/to/testRunner.js`.', + type: 'string' + }, + testSequencer: { + description: + 'Allows to specify a custom test sequencer. The default is ' + + '`@jest/test-sequencer`. A path to a custom test sequencer can be ' + + 'provided: `/path/to/testSequencer.js`', + type: 'string' + }, + testTimeout: { + description: 'This option sets the default timeouts of test cases.', + type: 'number' + }, + transform: { + description: + 'A JSON string which maps from regular expressions to paths ' + + 'to transformers.', + type: 'string' + }, + transformIgnorePatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all source file paths before transformation.', + string: true, + type: 'array' + }, + unmockedModulePathPatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all modules before the module loader will automatically ' + + 'return a mock for them.', + string: true, + type: 'array' + }, + updateSnapshot: { + alias: 'u', + description: + 'Use this flag to re-record snapshots. ' + + 'Can be used together with a test suite pattern or with ' + + '`--testNamePattern` to re-record snapshot for test matching ' + + 'the pattern', + type: 'boolean' + }, + useStderr: { + description: 'Divert all output to stderr.', + type: 'boolean' + }, + verbose: { + description: + 'Display individual test results with the test suite hierarchy.', + type: 'boolean' + }, + watch: { + description: + 'Watch files for changes and rerun tests related to ' + + 'changed files. If you want to re-run all tests when a file has ' + + 'changed, use the `--watchAll` option.', + type: 'boolean' + }, + watchAll: { + description: + 'Watch files for changes and rerun all tests. If you want ' + + 'to re-run only the tests related to the changed files, use the ' + + '`--watch` option.', + type: 'boolean' + }, + watchPathIgnorePatterns: { + description: + 'An array of regexp pattern strings that are matched ' + + 'against all paths before trigger test re-run in watch mode. ' + + 'If the test path matches any of the patterns, it will be skipped.', + string: true, + type: 'array' + }, + watchman: { + description: + 'Whether to use watchman for file crawling. Disable using ' + + '--no-watchman.', + type: 'boolean' + } +}; +exports.options = options; diff --git a/node_modules/jest-cli/build/index.d.ts b/node_modules/jest-cli/build/index.d.ts new file mode 100644 index 0000000..2e38204 --- /dev/null +++ b/node_modules/jest-cli/build/index.d.ts @@ -0,0 +1,12 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare function run( + maybeArgv?: Array, + project?: string, +): Promise; + +export {}; diff --git a/node_modules/jest-cli/build/index.js b/node_modules/jest-cli/build/index.js new file mode 100644 index 0000000..d1fd94e --- /dev/null +++ b/node_modules/jest-cli/build/index.js @@ -0,0 +1,12 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'run', { + enumerable: true, + get: function () { + return _run.run; + } +}); +var _run = require('./run'); diff --git a/node_modules/jest-cli/build/init/errors.js b/node_modules/jest-cli/build/init/errors.js new file mode 100644 index 0000000..6850ccb --- /dev/null +++ b/node_modules/jest-cli/build/init/errors.js @@ -0,0 +1,34 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.NotFoundPackageJsonError = exports.MalformedPackageJsonError = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class NotFoundPackageJsonError extends Error { + constructor(rootDir) { + super(`Could not find a "package.json" file in ${rootDir}`); + this.name = ''; + // eslint-disable-next-line @typescript-eslint/no-empty-function + Error.captureStackTrace(this, () => {}); + } +} +exports.NotFoundPackageJsonError = NotFoundPackageJsonError; +class MalformedPackageJsonError extends Error { + constructor(packageJsonPath) { + super( + `There is malformed json in ${packageJsonPath}\n` + + 'Fix it, and then run "jest --init"' + ); + this.name = ''; + // eslint-disable-next-line @typescript-eslint/no-empty-function + Error.captureStackTrace(this, () => {}); + } +} +exports.MalformedPackageJsonError = MalformedPackageJsonError; diff --git a/node_modules/jest-cli/build/init/generateConfigFile.js b/node_modules/jest-cli/build/init/generateConfigFile.js new file mode 100644 index 0000000..4eb9ae0 --- /dev/null +++ b/node_modules/jest-cli/build/init/generateConfigFile.js @@ -0,0 +1,85 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestConfig() { + const data = require('jest-config'); + _jestConfig = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const stringifyOption = (option, map, linePrefix = '') => { + const optionDescription = ` // ${_jestConfig().descriptions[option]}`; + const stringifiedObject = `${option}: ${JSON.stringify( + map[option], + null, + 2 + )}`; + return `${optionDescription}\n${stringifiedObject + .split('\n') + .map(line => ` ${linePrefix}${line}`) + .join('\n')},\n`; +}; +const generateConfigFile = (results, generateEsm = false) => { + const {useTypescript, coverage, coverageProvider, clearMocks, environment} = + results; + const overrides = {}; + if (coverage) { + Object.assign(overrides, { + collectCoverage: true, + coverageDirectory: 'coverage' + }); + } + if (coverageProvider === 'v8') { + Object.assign(overrides, { + coverageProvider: 'v8' + }); + } + if (environment === 'jsdom') { + Object.assign(overrides, { + testEnvironment: 'jsdom' + }); + } + if (clearMocks) { + Object.assign(overrides, { + clearMocks: true + }); + } + const overrideKeys = Object.keys(overrides); + const properties = []; + for (const option in _jestConfig().descriptions) { + const opt = option; + if (overrideKeys.includes(opt)) { + properties.push(stringifyOption(opt, overrides)); + } else { + properties.push(stringifyOption(opt, _jestConfig().defaults, '// ')); + } + } + const configHeaderMessage = `/* + * For a detailed explanation regarding each configuration property${ + useTypescript ? ' and type check' : '' + }, visit: + * https://jestjs.io/docs/configuration + */ + +`; + return `${ + configHeaderMessage + + (useTypescript || generateEsm + ? 'export default {\n' + : 'module.exports = {\n') + + properties.join('\n') + }};\n`; +}; +var _default = generateConfigFile; +exports.default = _default; diff --git a/node_modules/jest-cli/build/init/index.js b/node_modules/jest-cli/build/init/index.js new file mode 100644 index 0000000..81c40ef --- /dev/null +++ b/node_modules/jest-cli/build/init/index.js @@ -0,0 +1,211 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = init; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _prompts() { + const data = _interopRequireDefault(require('prompts')); + _prompts = function () { + return data; + }; + return data; +} +function _jestConfig() { + const data = require('jest-config'); + _jestConfig = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _errors = require('./errors'); +var _generateConfigFile = _interopRequireDefault( + require('./generateConfigFile') +); +var _modifyPackageJson = _interopRequireDefault(require('./modifyPackageJson')); +var _questions = _interopRequireWildcard(require('./questions')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const { + JEST_CONFIG_BASE_NAME, + JEST_CONFIG_EXT_MJS, + JEST_CONFIG_EXT_JS, + JEST_CONFIG_EXT_TS, + JEST_CONFIG_EXT_ORDER, + PACKAGE_JSON +} = _jestConfig().constants; +const getConfigFilename = ext => JEST_CONFIG_BASE_NAME + ext; +async function init(rootDir = (0, _jestUtil().tryRealpath)(process.cwd())) { + // prerequisite checks + const projectPackageJsonPath = path().join(rootDir, PACKAGE_JSON); + if (!fs().existsSync(projectPackageJsonPath)) { + throw new _errors.NotFoundPackageJsonError(rootDir); + } + const questions = _questions.default.slice(0); + let hasJestProperty = false; + let projectPackageJson; + try { + projectPackageJson = JSON.parse( + fs().readFileSync(projectPackageJsonPath, 'utf-8') + ); + } catch { + throw new _errors.MalformedPackageJsonError(projectPackageJsonPath); + } + if (projectPackageJson.jest) { + hasJestProperty = true; + } + const existingJestConfigExt = JEST_CONFIG_EXT_ORDER.find(ext => + fs().existsSync(path().join(rootDir, getConfigFilename(ext))) + ); + if (hasJestProperty || existingJestConfigExt) { + const result = await (0, _prompts().default)({ + initial: true, + message: + 'It seems that you already have a jest configuration, do you want to override it?', + name: 'continue', + type: 'confirm' + }); + if (!result.continue) { + console.log(); + console.log('Aborting...'); + return; + } + } + + // Add test script installation only if needed + if ( + !projectPackageJson.scripts || + projectPackageJson.scripts.test !== 'jest' + ) { + questions.unshift(_questions.testScriptQuestion); + } + + // Start the init process + console.log(); + console.log( + _chalk().default.underline( + 'The following questions will help Jest to create a suitable configuration for your project\n' + ) + ); + let promptAborted = false; + const results = await (0, _prompts().default)(questions, { + onCancel: () => { + promptAborted = true; + } + }); + if (promptAborted) { + console.log(); + console.log('Aborting...'); + return; + } + + // Determine if Jest should use JS or TS for the config file + const jestConfigFileExt = results.useTypescript + ? JEST_CONFIG_EXT_TS + : projectPackageJson.type === 'module' + ? JEST_CONFIG_EXT_MJS + : JEST_CONFIG_EXT_JS; + + // Determine Jest config path + const jestConfigPath = existingJestConfigExt + ? getConfigFilename(existingJestConfigExt) + : path().join(rootDir, getConfigFilename(jestConfigFileExt)); + const shouldModifyScripts = results.scripts; + if (shouldModifyScripts || hasJestProperty) { + const modifiedPackageJson = (0, _modifyPackageJson.default)({ + projectPackageJson, + shouldModifyScripts + }); + fs().writeFileSync(projectPackageJsonPath, modifiedPackageJson); + console.log(''); + console.log( + `✏️ Modified ${_chalk().default.cyan(projectPackageJsonPath)}` + ); + } + const generatedConfig = (0, _generateConfigFile.default)( + results, + projectPackageJson.type === 'module' || + jestConfigPath.endsWith(JEST_CONFIG_EXT_MJS) + ); + fs().writeFileSync(jestConfigPath, generatedConfig); + console.log(''); + console.log( + `📝 Configuration file created at ${_chalk().default.cyan(jestConfigPath)}` + ); +} diff --git a/node_modules/jest-cli/build/init/modifyPackageJson.js b/node_modules/jest-cli/build/init/modifyPackageJson.js new file mode 100644 index 0000000..3a36805 --- /dev/null +++ b/node_modules/jest-cli/build/init/modifyPackageJson.js @@ -0,0 +1,26 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const modifyPackageJson = ({projectPackageJson, shouldModifyScripts}) => { + if (shouldModifyScripts) { + projectPackageJson.scripts + ? (projectPackageJson.scripts.test = 'jest') + : (projectPackageJson.scripts = { + test: 'jest' + }); + } + delete projectPackageJson.jest; + return `${JSON.stringify(projectPackageJson, null, 2)}\n`; +}; +var _default = modifyPackageJson; +exports.default = _default; diff --git a/node_modules/jest-cli/build/init/questions.js b/node_modules/jest-cli/build/init/questions.js new file mode 100644 index 0000000..fa5b8e0 --- /dev/null +++ b/node_modules/jest-cli/build/init/questions.js @@ -0,0 +1,76 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.testScriptQuestion = exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const defaultQuestions = [ + { + initial: false, + message: 'Would you like to use Typescript for the configuration file?', + name: 'useTypescript', + type: 'confirm' + }, + { + choices: [ + { + title: 'node', + value: 'node' + }, + { + title: 'jsdom (browser-like)', + value: 'jsdom' + } + ], + initial: 0, + message: 'Choose the test environment that will be used for testing', + name: 'environment', + type: 'select' + }, + { + initial: false, + message: 'Do you want Jest to add coverage reports?', + name: 'coverage', + type: 'confirm' + }, + { + choices: [ + { + title: 'v8', + value: 'v8' + }, + { + title: 'babel', + value: 'babel' + } + ], + initial: 0, + message: 'Which provider should be used to instrument code for coverage?', + name: 'coverageProvider', + type: 'select' + }, + { + initial: false, + message: + 'Automatically clear mock calls, instances, contexts and results before every test?', + name: 'clearMocks', + type: 'confirm' + } +]; +var _default = defaultQuestions; +exports.default = _default; +const testScriptQuestion = { + initial: true, + message: + 'Would you like to use Jest when running "test" script in "package.json"?', + name: 'scripts', + type: 'confirm' +}; +exports.testScriptQuestion = testScriptQuestion; diff --git a/node_modules/jest-cli/build/init/types.js b/node_modules/jest-cli/build/init/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-cli/build/init/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-cli/build/run.js b/node_modules/jest-cli/build/run.js new file mode 100644 index 0000000..de7b190 --- /dev/null +++ b/node_modules/jest-cli/build/run.js @@ -0,0 +1,227 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.buildArgv = buildArgv; +exports.run = run; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _exit() { + const data = _interopRequireDefault(require('exit')); + _exit = function () { + return data; + }; + return data; +} +function _yargs() { + const data = _interopRequireDefault(require('yargs')); + _yargs = function () { + return data; + }; + return data; +} +function _core() { + const data = require('@jest/core'); + _core = function () { + return data; + }; + return data; +} +function _jestConfig() { + const data = require('jest-config'); + _jestConfig = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _jestValidate() { + const data = require('jest-validate'); + _jestValidate = function () { + return data; + }; + return data; +} +var args = _interopRequireWildcard(require('./args')); +var _init = _interopRequireDefault(require('./init')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +async function run(maybeArgv, project) { + try { + const argv = await buildArgv(maybeArgv); + if (argv.init) { + await (0, _init.default)(); + return; + } + const projects = getProjectListFromCLIArgs(argv, project); + const {results, globalConfig} = await (0, _core().runCLI)(argv, projects); + readResultsAndExit(results, globalConfig); + } catch (error) { + (0, _jestUtil().clearLine)(process.stderr); + (0, _jestUtil().clearLine)(process.stdout); + if (error?.stack) { + console.error(_chalk().default.red(error.stack)); + } else { + console.error(_chalk().default.red(error)); + } + (0, _exit().default)(1); + throw error; + } +} +async function buildArgv(maybeArgv) { + const version = + (0, _core().getVersion)() + + (__dirname.includes(`packages${path().sep}jest-cli`) ? '-dev' : ''); + const rawArgv = maybeArgv || process.argv.slice(2); + const argv = await (0, _yargs().default)(rawArgv) + .usage(args.usage) + .version(version) + .alias('help', 'h') + .options(args.options) + .epilogue(args.docs) + .check(args.check).argv; + (0, _jestValidate().validateCLIOptions)( + argv, + { + ...args.options, + deprecationEntries: _jestConfig().deprecationEntries + }, + // strip leading dashes + Array.isArray(rawArgv) + ? rawArgv.map(rawArgv => rawArgv.replace(/^--?/, '')) + : Object.keys(rawArgv) + ); + + // strip dashed args + return Object.keys(argv).reduce( + (result, key) => { + if (!key.includes('-')) { + result[key] = argv[key]; + } + return result; + }, + { + $0: argv.$0, + _: argv._ + } + ); +} +const getProjectListFromCLIArgs = (argv, project) => { + const projects = argv.projects ? argv.projects : []; + if (project) { + projects.push(project); + } + if (!projects.length && process.platform === 'win32') { + try { + projects.push((0, _jestUtil().tryRealpath)(process.cwd())); + } catch { + // do nothing, just catch error + // process.binding('fs').realpath can throw, e.g. on mapped drives + } + } + if (!projects.length) { + projects.push(process.cwd()); + } + return projects; +}; +const readResultsAndExit = (result, globalConfig) => { + const code = !result || result.success ? 0 : globalConfig.testFailureExitCode; + + // Only exit if needed + process.on('exit', () => { + if (typeof code === 'number' && code !== 0) { + process.exitCode = code; + } + }); + if (globalConfig.forceExit) { + if (!globalConfig.detectOpenHandles) { + console.warn( + `${_chalk().default.bold( + 'Force exiting Jest: ' + )}Have you considered using \`--detectOpenHandles\` to detect ` + + 'async operations that kept running after all tests finished?' + ); + } + (0, _exit().default)(code); + } else if (!globalConfig.detectOpenHandles) { + setTimeout(() => { + console.warn( + _chalk().default.yellow.bold( + 'Jest did not exit one second after the test run has completed.\n\n' + ) + + _chalk().default.yellow( + 'This usually means that there are asynchronous operations that ' + + "weren't stopped in your tests. Consider running Jest with " + + '`--detectOpenHandles` to troubleshoot this issue.' + ) + ); + }, 1000).unref(); + } +}; diff --git a/node_modules/jest-cli/package.json b/node_modules/jest-cli/package.json new file mode 100644 index 0000000..e93934b --- /dev/null +++ b/node_modules/jest-cli/package.json @@ -0,0 +1,89 @@ +{ + "name": "jest-cli", + "description": "Delightful JavaScript Testing.", + "version": "29.2.2", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json", + "./bin/jest": "./bin/jest.js" + }, + "dependencies": { + "@jest/core": "^29.2.2", + "@jest/test-result": "^29.2.1", + "@jest/types": "^29.2.1", + "chalk": "^4.0.0", + "exit": "^0.1.2", + "graceful-fs": "^4.2.9", + "import-local": "^3.0.2", + "jest-config": "^29.2.2", + "jest-util": "^29.2.1", + "jest-validate": "^29.2.2", + "prompts": "^2.0.1", + "yargs": "^17.3.1" + }, + "devDependencies": { + "@types/exit": "^0.1.30", + "@types/graceful-fs": "^4.1.3", + "@types/prompts": "^2.0.1", + "@types/yargs": "^17.0.8" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + }, + "bin": { + "jest": "./bin/jest.js" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-cli" + }, + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "homepage": "https://jestjs.io/", + "license": "MIT", + "keywords": [ + "ava", + "babel", + "coverage", + "easy", + "expect", + "facebook", + "immersive", + "instant", + "jasmine", + "jest", + "jsdom", + "mocha", + "mocking", + "painless", + "qunit", + "runner", + "sandboxed", + "snapshot", + "tap", + "tape", + "test", + "testing", + "typescript", + "watch" + ], + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-config/LICENSE b/node_modules/jest-config/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-config/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-config/build/Defaults.js b/node_modules/jest-config/build/Defaults.js new file mode 100644 index 0000000..b1782c9 --- /dev/null +++ b/node_modules/jest-config/build/Defaults.js @@ -0,0 +1,127 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _path() { + const data = require('path'); + _path = function () { + return data; + }; + return data; +} +function _ciInfo() { + const data = require('ci-info'); + _ciInfo = function () { + return data; + }; + return data; +} +function _jestRegexUtil() { + const data = require('jest-regex-util'); + _jestRegexUtil = function () { + return data; + }; + return data; +} +var _constants = require('./constants'); +var _getCacheDirectory = _interopRequireDefault(require('./getCacheDirectory')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const NODE_MODULES_REGEXP = (0, _jestRegexUtil().replacePathSepForRegex)( + _constants.NODE_MODULES +); +const defaultOptions = { + automock: false, + bail: 0, + cache: true, + cacheDirectory: (0, _getCacheDirectory.default)(), + changedFilesWithAncestor: false, + ci: _ciInfo().isCI, + clearMocks: false, + collectCoverage: false, + coveragePathIgnorePatterns: [NODE_MODULES_REGEXP], + coverageProvider: 'babel', + coverageReporters: ['json', 'text', 'lcov', 'clover'], + detectLeaks: false, + detectOpenHandles: false, + errorOnDeprecated: false, + expand: false, + extensionsToTreatAsEsm: [], + fakeTimers: { + enableGlobally: false + }, + forceCoverageMatch: [], + globals: {}, + haste: { + computeSha1: false, + enableSymlinks: false, + forceNodeFilesystemAPI: true, + throwOnModuleCollision: false + }, + injectGlobals: true, + listTests: false, + maxConcurrency: 5, + maxWorkers: '50%', + moduleDirectories: ['node_modules'], + moduleFileExtensions: [ + 'js', + 'mjs', + 'cjs', + 'jsx', + 'ts', + 'tsx', + 'json', + 'node' + ], + moduleNameMapper: {}, + modulePathIgnorePatterns: [], + noStackTrace: false, + notify: false, + notifyMode: 'failure-change', + passWithNoTests: false, + prettierPath: 'prettier', + resetMocks: false, + resetModules: false, + restoreMocks: false, + roots: [''], + runTestsByPath: false, + runner: 'jest-runner', + setupFiles: [], + setupFilesAfterEnv: [], + skipFilter: false, + slowTestThreshold: 5, + snapshotFormat: { + escapeString: false, + printBasicPrototype: false + }, + snapshotSerializers: [], + testEnvironment: 'jest-environment-node', + testEnvironmentOptions: {}, + testFailureExitCode: 1, + testLocationInResults: false, + testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[tj]s?(x)'], + testPathIgnorePatterns: [NODE_MODULES_REGEXP], + testRegex: [], + testRunner: 'jest-circus/runner', + testSequencer: '@jest/test-sequencer', + transformIgnorePatterns: [ + NODE_MODULES_REGEXP, + `\\.pnp\\.[^\\${_path().sep}]+$` + ], + useStderr: false, + watch: false, + watchPathIgnorePatterns: [], + watchman: true +}; +var _default = defaultOptions; +exports.default = _default; diff --git a/node_modules/jest-config/build/Deprecated.js b/node_modules/jest-config/build/Deprecated.js new file mode 100644 index 0000000..4c4a27a --- /dev/null +++ b/node_modules/jest-config/build/Deprecated.js @@ -0,0 +1,85 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const deprecatedOptions = { + browser: () => + ` Option ${_chalk().default.bold( + '"browser"' + )} has been deprecated. Please install "browser-resolve" and use the "resolver" option in Jest configuration as shown in the documentation: https://jestjs.io/docs/configuration#resolver-string`, + collectCoverageOnlyFrom: _options => ` Option ${_chalk().default.bold( + '"collectCoverageOnlyFrom"' + )} was replaced by ${_chalk().default.bold('"collectCoverageFrom"')}. + + Please update your configuration.`, + extraGlobals: _options => ` Option ${_chalk().default.bold( + '"extraGlobals"' + )} was replaced by ${_chalk().default.bold('"sandboxInjectedGlobals"')}. + + Please update your configuration.`, + moduleLoader: _options => ` Option ${_chalk().default.bold( + '"moduleLoader"' + )} was replaced by ${_chalk().default.bold('"runtime"')}. + + Please update your configuration.`, + preprocessorIgnorePatterns: _options => ` Option ${_chalk().default.bold( + '"preprocessorIgnorePatterns"' + )} was replaced by ${_chalk().default.bold( + '"transformIgnorePatterns"' + )}, which support multiple preprocessors. + + Please update your configuration.`, + scriptPreprocessor: _options => ` Option ${_chalk().default.bold( + '"scriptPreprocessor"' + )} was replaced by ${_chalk().default.bold( + '"transform"' + )}, which support multiple preprocessors. + + Please update your configuration.`, + setupTestFrameworkScriptFile: _options => ` Option ${_chalk().default.bold( + '"setupTestFrameworkScriptFile"' + )} was replaced by configuration ${_chalk().default.bold( + '"setupFilesAfterEnv"' + )}, which supports multiple paths. + + Please update your configuration.`, + testPathDirs: _options => ` Option ${_chalk().default.bold( + '"testPathDirs"' + )} was replaced by ${_chalk().default.bold('"roots"')}. + + Please update your configuration. + `, + testURL: _options => ` Option ${_chalk().default.bold( + '"testURL"' + )} was replaced by passing the URL via ${_chalk().default.bold( + '"testEnvironmentOptions.url"' + )}. + + Please update your configuration.`, + timers: _options => ` Option ${_chalk().default.bold( + '"timers"' + )} was replaced by ${_chalk().default.bold('"fakeTimers"')}. + + Please update your configuration.` +}; +var _default = deprecatedOptions; +exports.default = _default; diff --git a/node_modules/jest-config/build/Descriptions.js b/node_modules/jest-config/build/Descriptions.js new file mode 100644 index 0000000..184e03d --- /dev/null +++ b/node_modules/jest-config/build/Descriptions.js @@ -0,0 +1,104 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const descriptions = { + automock: 'All imported modules in your tests should be mocked automatically', + bail: 'Stop running tests after `n` failures', + cacheDirectory: + 'The directory where Jest should store its cached dependency information', + clearMocks: + 'Automatically clear mock calls, instances, contexts and results before every test', + collectCoverage: + 'Indicates whether the coverage information should be collected while executing the test', + collectCoverageFrom: + 'An array of glob patterns indicating a set of files for which coverage information should be collected', + coverageDirectory: + 'The directory where Jest should output its coverage files', + coveragePathIgnorePatterns: + 'An array of regexp pattern strings used to skip coverage collection', + coverageProvider: + 'Indicates which provider should be used to instrument code for coverage', + coverageReporters: + 'A list of reporter names that Jest uses when writing coverage reports', + coverageThreshold: + 'An object that configures minimum threshold enforcement for coverage results', + dependencyExtractor: 'A path to a custom dependency extractor', + errorOnDeprecated: + 'Make calling deprecated APIs throw helpful error messages', + fakeTimers: 'The default configuration for fake timers', + forceCoverageMatch: + 'Force coverage collection from ignored files using an array of glob patterns', + globalSetup: + 'A path to a module which exports an async function that is triggered once before all test suites', + globalTeardown: + 'A path to a module which exports an async function that is triggered once after all test suites', + globals: + 'A set of global variables that need to be available in all test environments', + maxWorkers: + 'The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.', + moduleDirectories: + "An array of directory names to be searched recursively up from the requiring module's location", + moduleFileExtensions: 'An array of file extensions your modules use', + moduleNameMapper: + 'A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module', + modulePathIgnorePatterns: + "An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader", + notify: 'Activates notifications for test results', + notifyMode: + 'An enum that specifies notification mode. Requires { notify: true }', + preset: "A preset that is used as a base for Jest's configuration", + projects: 'Run tests from one or more projects', + reporters: 'Use this configuration option to add custom reporters to Jest', + resetMocks: 'Automatically reset mock state before every test', + resetModules: 'Reset the module registry before running each individual test', + resolver: 'A path to a custom resolver', + restoreMocks: + 'Automatically restore mock state and implementation before every test', + rootDir: + 'The root directory that Jest should scan for tests and modules within', + roots: + 'A list of paths to directories that Jest should use to search for files in', + runner: + "Allows you to use a custom runner instead of Jest's default test runner", + setupFiles: + 'The paths to modules that run some code to configure or set up the testing environment before each test', + setupFilesAfterEnv: + 'A list of paths to modules that run some code to configure or set up the testing framework before each test', + slowTestThreshold: + 'The number of seconds after which a test is considered as slow and reported as such in the results.', + snapshotSerializers: + 'A list of paths to snapshot serializer modules Jest should use for snapshot testing', + testEnvironment: 'The test environment that will be used for testing', + testEnvironmentOptions: 'Options that will be passed to the testEnvironment', + testLocationInResults: 'Adds a location field to test results', + testMatch: 'The glob patterns Jest uses to detect test files', + testPathIgnorePatterns: + 'An array of regexp pattern strings that are matched against all test paths, matched tests are skipped', + testRegex: + 'The regexp pattern or array of patterns that Jest uses to detect test files', + testResultsProcessor: + 'This option allows the use of a custom results processor', + testRunner: 'This option allows use of a custom test runner', + transform: 'A map from regular expressions to paths to transformers', + transformIgnorePatterns: + 'An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation', + unmockedModulePathPatterns: + 'An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them', + verbose: + 'Indicates whether each individual test should be reported during the run', + watchPathIgnorePatterns: + 'An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode', + watchman: 'Whether to use watchman for file crawling' +}; +var _default = descriptions; +exports.default = _default; diff --git a/node_modules/jest-config/build/ReporterValidationErrors.js b/node_modules/jest-config/build/ReporterValidationErrors.js new file mode 100644 index 0000000..66c08a3 --- /dev/null +++ b/node_modules/jest-config/build/ReporterValidationErrors.js @@ -0,0 +1,122 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.createArrayReporterError = createArrayReporterError; +exports.createReporterError = createReporterError; +exports.validateReporters = validateReporters; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestGetType() { + const data = require('jest-get-type'); + _jestGetType = function () { + return data; + }; + return data; +} +function _jestValidate() { + const data = require('jest-validate'); + _jestValidate = function () { + return data; + }; + return data; +} +var _utils = require('./utils'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const validReporterTypes = ['array', 'string']; +const ERROR = `${_utils.BULLET}Reporter Validation Error`; + +/** + * Reporter Validation Error is thrown if the given arguments + * within the reporter are not valid. + * + * This is a highly specific reporter error and in the future will be + * merged with jest-validate. Till then, we can make use of it. It works + * and that's what counts most at this time. + */ +function createReporterError(reporterIndex, reporterValue) { + const errorMessage = + ` Reporter at index ${reporterIndex} must be of type:\n` + + ` ${_chalk().default.bold.green(validReporterTypes.join(' or '))}\n` + + ' but instead received:\n' + + ` ${_chalk().default.bold.red( + (0, _jestGetType().getType)(reporterValue) + )}`; + return new (_jestValidate().ValidationError)( + ERROR, + errorMessage, + _utils.DOCUMENTATION_NOTE + ); +} +function createArrayReporterError( + arrayReporter, + reporterIndex, + valueIndex, + value, + expectedType, + valueName +) { + const errorMessage = + ` Unexpected value for ${valueName} ` + + `at index ${valueIndex} of reporter at index ${reporterIndex}\n` + + ' Expected:\n' + + ` ${_chalk().default.bold.red(expectedType)}\n` + + ' Got:\n' + + ` ${_chalk().default.bold.green((0, _jestGetType().getType)(value))}\n` + + ' Reporter configuration:\n' + + ` ${_chalk().default.bold.green( + JSON.stringify(arrayReporter, null, 2).split('\n').join('\n ') + )}`; + return new (_jestValidate().ValidationError)( + ERROR, + errorMessage, + _utils.DOCUMENTATION_NOTE + ); +} +function validateReporters(reporterConfig) { + return reporterConfig.every((reporter, index) => { + if (Array.isArray(reporter)) { + validateArrayReporter(reporter, index); + } else if (typeof reporter !== 'string') { + throw createReporterError(index, reporter); + } + return true; + }); +} +function validateArrayReporter(arrayReporter, reporterIndex) { + const [path, options] = arrayReporter; + if (typeof path !== 'string') { + throw createArrayReporterError( + arrayReporter, + reporterIndex, + 0, + path, + 'string', + 'Path' + ); + } else if (typeof options !== 'object') { + throw createArrayReporterError( + arrayReporter, + reporterIndex, + 1, + options, + 'object', + 'Reporter Configuration' + ); + } +} diff --git a/node_modules/jest-config/build/ValidConfig.js b/node_modules/jest-config/build/ValidConfig.js new file mode 100644 index 0000000..5e204d6 --- /dev/null +++ b/node_modules/jest-config/build/ValidConfig.js @@ -0,0 +1,221 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestRegexUtil() { + const data = require('jest-regex-util'); + _jestRegexUtil = function () { + return data; + }; + return data; +} +function _jestValidate() { + const data = require('jest-validate'); + _jestValidate = function () { + return data; + }; + return data; +} +function _prettyFormat() { + const data = require('pretty-format'); + _prettyFormat = function () { + return data; + }; + return data; +} +var _constants = require('./constants'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const NODE_MODULES_REGEXP = (0, _jestRegexUtil().replacePathSepForRegex)( + _constants.NODE_MODULES +); +const initialOptions = { + automock: false, + bail: (0, _jestValidate().multipleValidOptions)(false, 0), + cache: true, + cacheDirectory: '/tmp/user/jest', + changedFilesWithAncestor: false, + changedSince: 'master', + ci: false, + clearMocks: false, + collectCoverage: true, + collectCoverageFrom: ['src', '!public'], + coverageDirectory: 'coverage', + coveragePathIgnorePatterns: [NODE_MODULES_REGEXP], + coverageProvider: 'v8', + coverageReporters: ['json', 'text', 'lcov', 'clover'], + coverageThreshold: { + global: { + branches: 50, + functions: 100, + lines: 100, + statements: 100 + } + }, + dependencyExtractor: '/dependencyExtractor.js', + detectLeaks: false, + detectOpenHandles: false, + displayName: (0, _jestValidate().multipleValidOptions)('test-config', { + color: 'blue', + name: 'test-config' + }), + errorOnDeprecated: false, + expand: false, + extensionsToTreatAsEsm: [], + fakeTimers: { + advanceTimers: (0, _jestValidate().multipleValidOptions)(40, true), + doNotFake: [ + 'Date', + 'hrtime', + 'nextTick', + 'performance', + 'queueMicrotask', + 'requestAnimationFrame', + 'cancelAnimationFrame', + 'requestIdleCallback', + 'cancelIdleCallback', + 'setImmediate', + 'clearImmediate', + 'setInterval', + 'clearInterval', + 'setTimeout', + 'clearTimeout' + ], + enableGlobally: true, + legacyFakeTimers: false, + now: 1483228800000, + timerLimit: 1000 + }, + filter: '/filter.js', + forceCoverageMatch: ['**/*.t.js'], + forceExit: false, + globalSetup: 'setup.js', + globalTeardown: 'teardown.js', + globals: { + __DEV__: true + }, + haste: { + computeSha1: true, + defaultPlatform: 'ios', + enableSymlinks: false, + forceNodeFilesystemAPI: true, + hasteImplModulePath: '/haste_impl.js', + hasteMapModulePath: '', + platforms: ['ios', 'android'], + retainAllFiles: false, + throwOnModuleCollision: false + }, + id: 'string', + injectGlobals: true, + json: false, + lastCommit: false, + listTests: false, + logHeapUsage: true, + maxConcurrency: 5, + maxWorkers: '50%', + moduleDirectories: ['node_modules'], + moduleFileExtensions: [ + 'js', + 'mjs', + 'cjs', + 'json', + 'jsx', + 'ts', + 'tsx', + 'node' + ], + moduleNameMapper: { + '^React$': '/node_modules/react' + }, + modulePathIgnorePatterns: ['/build/'], + modulePaths: ['/shared/vendor/modules'], + noStackTrace: false, + notify: false, + notifyMode: 'failure-change', + onlyChanged: false, + onlyFailures: false, + passWithNoTests: false, + preset: 'react-native', + prettierPath: '/node_modules/prettier', + projects: ['project-a', 'project-b/'], + reporters: [ + 'default', + 'custom-reporter-1', + [ + 'custom-reporter-2', + { + configValue: true + } + ] + ], + resetMocks: false, + resetModules: false, + resolver: '/resolver.js', + restoreMocks: false, + rootDir: '/', + roots: [''], + runTestsByPath: false, + runner: 'jest-runner', + runtime: '', + sandboxInjectedGlobals: [], + setupFiles: ['/setup.js'], + setupFilesAfterEnv: ['/testSetupFile.js'], + showSeed: false, + silent: true, + skipFilter: false, + skipNodeResolution: false, + slowTestThreshold: 5, + snapshotFormat: _prettyFormat().DEFAULT_OPTIONS, + snapshotResolver: '/snapshotResolver.js', + snapshotSerializers: ['my-serializer-module'], + testEnvironment: 'jest-environment-node', + testEnvironmentOptions: { + url: 'http://localhost', + userAgent: 'Agent/007' + }, + testFailureExitCode: 1, + testLocationInResults: false, + testMatch: ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'], + testNamePattern: 'test signature', + testPathIgnorePatterns: [NODE_MODULES_REGEXP], + testRegex: (0, _jestValidate().multipleValidOptions)( + '(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$', + ['/__tests__/\\.test\\.[jt]sx?$', '/__tests__/\\.spec\\.[jt]sx?$'] + ), + testResultsProcessor: 'processor-node-module', + testRunner: 'circus', + testSequencer: '@jest/test-sequencer', + testTimeout: 5000, + transform: { + '\\.js$': '/preprocessor.js' + }, + transformIgnorePatterns: [NODE_MODULES_REGEXP], + unmockedModulePathPatterns: ['mock'], + updateSnapshot: true, + useStderr: false, + verbose: false, + watch: false, + watchAll: false, + watchPathIgnorePatterns: ['/e2e/'], + watchPlugins: [ + 'path/to/yourWatchPlugin', + [ + 'jest-watch-typeahead/filename', + { + key: 'k', + prompt: 'do something with my custom prompt' + } + ] + ], + watchman: true, + workerIdleMemoryLimit: (0, _jestValidate().multipleValidOptions)(0.2, '50%') +}; +var _default = initialOptions; +exports.default = _default; diff --git a/node_modules/jest-config/build/color.js b/node_modules/jest-config/build/color.js new file mode 100644 index 0000000..24a26ad --- /dev/null +++ b/node_modules/jest-config/build/color.js @@ -0,0 +1,31 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getDisplayNameColor = void 0; +function _crypto() { + const data = require('crypto'); + _crypto = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const colors = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']; +const getDisplayNameColor = seed => { + if (seed === undefined) { + return 'white'; + } + const hash = (0, _crypto().createHash)('sha256'); + hash.update(seed); + const num = hash.digest().readUInt32LE(0); + return colors[num % colors.length]; +}; +exports.getDisplayNameColor = getDisplayNameColor; diff --git a/node_modules/jest-config/build/constants.js b/node_modules/jest-config/build/constants.js new file mode 100644 index 0000000..ec0c238 --- /dev/null +++ b/node_modules/jest-config/build/constants.js @@ -0,0 +1,96 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.PACKAGE_JSON = + exports.NODE_MODULES = + exports.JEST_CONFIG_EXT_TS = + exports.JEST_CONFIG_EXT_ORDER = + exports.JEST_CONFIG_EXT_MJS = + exports.JEST_CONFIG_EXT_JSON = + exports.JEST_CONFIG_EXT_JS = + exports.JEST_CONFIG_EXT_CJS = + exports.JEST_CONFIG_BASE_NAME = + exports.DEFAULT_JS_PATTERN = + void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const NODE_MODULES = `${path().sep}node_modules${path().sep}`; +exports.NODE_MODULES = NODE_MODULES; +const DEFAULT_JS_PATTERN = '\\.[jt]sx?$'; +exports.DEFAULT_JS_PATTERN = DEFAULT_JS_PATTERN; +const PACKAGE_JSON = 'package.json'; +exports.PACKAGE_JSON = PACKAGE_JSON; +const JEST_CONFIG_BASE_NAME = 'jest.config'; +exports.JEST_CONFIG_BASE_NAME = JEST_CONFIG_BASE_NAME; +const JEST_CONFIG_EXT_CJS = '.cjs'; +exports.JEST_CONFIG_EXT_CJS = JEST_CONFIG_EXT_CJS; +const JEST_CONFIG_EXT_MJS = '.mjs'; +exports.JEST_CONFIG_EXT_MJS = JEST_CONFIG_EXT_MJS; +const JEST_CONFIG_EXT_JS = '.js'; +exports.JEST_CONFIG_EXT_JS = JEST_CONFIG_EXT_JS; +const JEST_CONFIG_EXT_TS = '.ts'; +exports.JEST_CONFIG_EXT_TS = JEST_CONFIG_EXT_TS; +const JEST_CONFIG_EXT_JSON = '.json'; +exports.JEST_CONFIG_EXT_JSON = JEST_CONFIG_EXT_JSON; +const JEST_CONFIG_EXT_ORDER = Object.freeze([ + JEST_CONFIG_EXT_JS, + JEST_CONFIG_EXT_TS, + JEST_CONFIG_EXT_MJS, + JEST_CONFIG_EXT_CJS, + JEST_CONFIG_EXT_JSON +]); +exports.JEST_CONFIG_EXT_ORDER = JEST_CONFIG_EXT_ORDER; diff --git a/node_modules/jest-config/build/getCacheDirectory.js b/node_modules/jest-config/build/getCacheDirectory.js new file mode 100644 index 0000000..e2c660a --- /dev/null +++ b/node_modules/jest-config/build/getCacheDirectory.js @@ -0,0 +1,91 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _os() { + const data = require('os'); + _os = function () { + return data; + }; + return data; +} +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const getCacheDirectory = () => { + const {getuid} = process; + const tmpdirPath = path().join( + (0, _jestUtil().tryRealpath)((0, _os().tmpdir)()), + 'jest' + ); + if (getuid == null) { + return tmpdirPath; + } else { + // On some platforms tmpdir() is `/tmp`, causing conflicts between different + // users and permission issues. Adding an additional subdivision by UID can + // help. + return `${tmpdirPath}_${getuid.call(process).toString(36)}`; + } +}; +var _default = getCacheDirectory; +exports.default = _default; diff --git a/node_modules/jest-config/build/getMaxWorkers.js b/node_modules/jest-config/build/getMaxWorkers.js new file mode 100644 index 0000000..2b70cb8 --- /dev/null +++ b/node_modules/jest-config/build/getMaxWorkers.js @@ -0,0 +1,52 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getMaxWorkers; +function _os() { + const data = require('os'); + _os = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getMaxWorkers(argv, defaultOptions) { + if (argv.runInBand) { + return 1; + } else if (argv.maxWorkers) { + return parseWorkers(argv.maxWorkers); + } else if (defaultOptions && defaultOptions.maxWorkers) { + return parseWorkers(defaultOptions.maxWorkers); + } else { + // In watch mode, Jest should be unobtrusive and not use all available CPUs. + const cpusInfo = (0, _os().cpus)(); + const numCpus = cpusInfo?.length ?? 1; + const isWatchModeEnabled = argv.watch || argv.watchAll; + return Math.max( + isWatchModeEnabled ? Math.floor(numCpus / 2) : numCpus - 1, + 1 + ); + } +} +const parseWorkers = maxWorkers => { + const parsed = parseInt(maxWorkers.toString(), 10); + if ( + typeof maxWorkers === 'string' && + maxWorkers.trim().endsWith('%') && + parsed > 0 && + parsed <= 100 + ) { + const numCpus = (0, _os().cpus)().length; + const workers = Math.floor((parsed / 100) * numCpus); + return Math.max(workers, 1); + } + return parsed > 0 ? parsed : 1; +}; diff --git a/node_modules/jest-config/build/index.d.ts b/node_modules/jest-config/build/index.d.ts new file mode 100644 index 0000000..0da1d81 --- /dev/null +++ b/node_modules/jest-config/build/index.d.ts @@ -0,0 +1,146 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config} from '@jest/types'; +import type {DeprecatedOptions} from 'jest-validate'; + +declare type AllOptions = Config.ProjectConfig & Config.GlobalConfig; + +declare namespace constants { + export { + NODE_MODULES, + DEFAULT_JS_PATTERN, + PACKAGE_JSON, + JEST_CONFIG_BASE_NAME, + JEST_CONFIG_EXT_CJS, + JEST_CONFIG_EXT_MJS, + JEST_CONFIG_EXT_JS, + JEST_CONFIG_EXT_TS, + JEST_CONFIG_EXT_JSON, + JEST_CONFIG_EXT_ORDER, + }; +} +export {constants}; + +declare const DEFAULT_JS_PATTERN = '\\.[jt]sx?$'; + +export declare const defaults: Config.DefaultOptions; + +export declare const deprecationEntries: DeprecatedOptions; + +export declare const descriptions: { + [key in keyof Config.InitialOptions]: string; +}; + +export declare const isJSONString: ( + text?: JSONString | string, +) => text is JSONString; + +declare const JEST_CONFIG_BASE_NAME = 'jest.config'; + +declare const JEST_CONFIG_EXT_CJS = '.cjs'; + +declare const JEST_CONFIG_EXT_JS = '.js'; + +declare const JEST_CONFIG_EXT_JSON = '.json'; + +declare const JEST_CONFIG_EXT_MJS = '.mjs'; + +declare const JEST_CONFIG_EXT_ORDER: readonly string[]; + +declare const JEST_CONFIG_EXT_TS = '.ts'; + +declare type JSONString = string & { + readonly $$type: never; +}; + +declare const NODE_MODULES: string; + +export declare function normalize( + initialOptions: Config.InitialOptions, + argv: Config.Argv, + configPath?: string | null, + projectIndex?: number, +): Promise<{ + hasDeprecationWarnings: boolean; + options: AllOptions; +}>; + +declare const PACKAGE_JSON = 'package.json'; + +declare type ReadConfig = { + configPath: string | null | undefined; + globalConfig: Config.GlobalConfig; + hasDeprecationWarnings: boolean; + projectConfig: Config.ProjectConfig; +}; + +export declare function readConfig( + argv: Config.Argv, + packageRootOrConfig: string | Config.InitialOptions, + skipArgvConfigOption?: boolean, + parentConfigDirname?: string | null, + projectIndex?: number, + skipMultipleConfigError?: boolean, +): Promise; + +export declare function readConfigs( + argv: Config.Argv, + projectPaths: Array, +): Promise<{ + globalConfig: Config.GlobalConfig; + configs: Array; + hasDeprecationWarnings: boolean; +}>; + +/** + * Reads the jest config, without validating them or filling it out with defaults. + * @param config The path to the file or serialized config. + * @param param1 Additional options + * @returns The raw initial config (not validated) + */ +export declare function readInitialOptions( + config?: string, + { + packageRootOrConfig, + parentConfigDirname, + readFromCwd, + skipMultipleConfigError, + }?: ReadJestConfigOptions, +): Promise<{ + config: Config.InitialOptions; + configPath: string | null; +}>; + +export declare interface ReadJestConfigOptions { + /** + * The package root or deserialized config (default is cwd) + */ + packageRootOrConfig?: string | Config.InitialOptions; + /** + * When the `packageRootOrConfig` contains config, this parameter should + * contain the dirname of the parent config + */ + parentConfigDirname?: null | string; + /** + * Indicates whether or not to read the specified config file from disk. + * When true, jest will read try to read config from the current working directory. + * (default is false) + */ + readFromCwd?: boolean; + /** + * Indicates whether or not to ignore the error of jest finding multiple config files. + * (default is false) + */ + skipMultipleConfigError?: boolean; +} + +export declare const replaceRootDirInPath: ( + rootDir: string, + filePath: string, +) => string; + +export {}; diff --git a/node_modules/jest-config/build/index.js b/node_modules/jest-config/build/index.js new file mode 100644 index 0000000..749ec20 --- /dev/null +++ b/node_modules/jest-config/build/index.js @@ -0,0 +1,482 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.constants = void 0; +Object.defineProperty(exports, 'defaults', { + enumerable: true, + get: function () { + return _Defaults.default; + } +}); +Object.defineProperty(exports, 'deprecationEntries', { + enumerable: true, + get: function () { + return _Deprecated.default; + } +}); +Object.defineProperty(exports, 'descriptions', { + enumerable: true, + get: function () { + return _Descriptions.default; + } +}); +Object.defineProperty(exports, 'isJSONString', { + enumerable: true, + get: function () { + return _utils.isJSONString; + } +}); +Object.defineProperty(exports, 'normalize', { + enumerable: true, + get: function () { + return _normalize.default; + } +}); +exports.readConfig = readConfig; +exports.readConfigs = readConfigs; +exports.readInitialOptions = readInitialOptions; +Object.defineProperty(exports, 'replaceRootDirInPath', { + enumerable: true, + get: function () { + return _utils.replaceRootDirInPath; + } +}); +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var constants = _interopRequireWildcard(require('./constants')); +exports.constants = constants; +var _normalize = _interopRequireDefault(require('./normalize')); +var _readConfigFileAndSetRootDir = _interopRequireDefault( + require('./readConfigFileAndSetRootDir') +); +var _resolveConfigPath = _interopRequireDefault(require('./resolveConfigPath')); +var _utils = require('./utils'); +var _Deprecated = _interopRequireDefault(require('./Deprecated')); +var _Defaults = _interopRequireDefault(require('./Defaults')); +var _Descriptions = _interopRequireDefault(require('./Descriptions')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +async function readConfig( + argv, + packageRootOrConfig, + // Whether it needs to look into `--config` arg passed to CLI. + // It only used to read initial config. If the initial config contains + // `project` property, we don't want to read `--config` value and rather + // read individual configs for every project. + skipArgvConfigOption, + parentConfigDirname, + projectIndex = Infinity, + skipMultipleConfigError = false +) { + const {config: initialOptions, configPath} = await readInitialOptions( + argv.config, + { + packageRootOrConfig, + parentConfigDirname, + readFromCwd: skipArgvConfigOption, + skipMultipleConfigError + } + ); + const {options, hasDeprecationWarnings} = await (0, _normalize.default)( + initialOptions, + argv, + configPath, + projectIndex + ); + const {globalConfig, projectConfig} = groupOptions(options); + return { + configPath, + globalConfig, + hasDeprecationWarnings, + projectConfig + }; +} +const groupOptions = options => ({ + globalConfig: Object.freeze({ + bail: options.bail, + changedFilesWithAncestor: options.changedFilesWithAncestor, + changedSince: options.changedSince, + ci: options.ci, + collectCoverage: options.collectCoverage, + collectCoverageFrom: options.collectCoverageFrom, + coverageDirectory: options.coverageDirectory, + coverageProvider: options.coverageProvider, + coverageReporters: options.coverageReporters, + coverageThreshold: options.coverageThreshold, + detectLeaks: options.detectLeaks, + detectOpenHandles: options.detectOpenHandles, + errorOnDeprecated: options.errorOnDeprecated, + expand: options.expand, + filter: options.filter, + findRelatedTests: options.findRelatedTests, + forceExit: options.forceExit, + globalSetup: options.globalSetup, + globalTeardown: options.globalTeardown, + json: options.json, + lastCommit: options.lastCommit, + listTests: options.listTests, + logHeapUsage: options.logHeapUsage, + maxConcurrency: options.maxConcurrency, + maxWorkers: options.maxWorkers, + noSCM: undefined, + noStackTrace: options.noStackTrace, + nonFlagArgs: options.nonFlagArgs, + notify: options.notify, + notifyMode: options.notifyMode, + onlyChanged: options.onlyChanged, + onlyFailures: options.onlyFailures, + outputFile: options.outputFile, + passWithNoTests: options.passWithNoTests, + projects: options.projects, + replname: options.replname, + reporters: options.reporters, + rootDir: options.rootDir, + runTestsByPath: options.runTestsByPath, + seed: options.seed, + shard: options.shard, + showSeed: options.showSeed, + silent: options.silent, + skipFilter: options.skipFilter, + snapshotFormat: options.snapshotFormat, + testFailureExitCode: options.testFailureExitCode, + testNamePattern: options.testNamePattern, + testPathPattern: options.testPathPattern, + testResultsProcessor: options.testResultsProcessor, + testSequencer: options.testSequencer, + testTimeout: options.testTimeout, + updateSnapshot: options.updateSnapshot, + useStderr: options.useStderr, + verbose: options.verbose, + watch: options.watch, + watchAll: options.watchAll, + watchPlugins: options.watchPlugins, + watchman: options.watchman, + workerIdleMemoryLimit: options.workerIdleMemoryLimit + }), + projectConfig: Object.freeze({ + automock: options.automock, + cache: options.cache, + cacheDirectory: options.cacheDirectory, + clearMocks: options.clearMocks, + coveragePathIgnorePatterns: options.coveragePathIgnorePatterns, + cwd: options.cwd, + dependencyExtractor: options.dependencyExtractor, + detectLeaks: options.detectLeaks, + detectOpenHandles: options.detectOpenHandles, + displayName: options.displayName, + errorOnDeprecated: options.errorOnDeprecated, + extensionsToTreatAsEsm: options.extensionsToTreatAsEsm, + fakeTimers: options.fakeTimers, + filter: options.filter, + forceCoverageMatch: options.forceCoverageMatch, + globalSetup: options.globalSetup, + globalTeardown: options.globalTeardown, + globals: options.globals, + haste: options.haste, + id: options.id, + injectGlobals: options.injectGlobals, + moduleDirectories: options.moduleDirectories, + moduleFileExtensions: options.moduleFileExtensions, + moduleNameMapper: options.moduleNameMapper, + modulePathIgnorePatterns: options.modulePathIgnorePatterns, + modulePaths: options.modulePaths, + prettierPath: options.prettierPath, + resetMocks: options.resetMocks, + resetModules: options.resetModules, + resolver: options.resolver, + restoreMocks: options.restoreMocks, + rootDir: options.rootDir, + roots: options.roots, + runner: options.runner, + runtime: options.runtime, + sandboxInjectedGlobals: options.sandboxInjectedGlobals, + setupFiles: options.setupFiles, + setupFilesAfterEnv: options.setupFilesAfterEnv, + skipFilter: options.skipFilter, + skipNodeResolution: options.skipNodeResolution, + slowTestThreshold: options.slowTestThreshold, + snapshotFormat: options.snapshotFormat, + snapshotResolver: options.snapshotResolver, + snapshotSerializers: options.snapshotSerializers, + testEnvironment: options.testEnvironment, + testEnvironmentOptions: options.testEnvironmentOptions, + testLocationInResults: options.testLocationInResults, + testMatch: options.testMatch, + testPathIgnorePatterns: options.testPathIgnorePatterns, + testRegex: options.testRegex, + testRunner: options.testRunner, + transform: options.transform, + transformIgnorePatterns: options.transformIgnorePatterns, + unmockedModulePathPatterns: options.unmockedModulePathPatterns, + watchPathIgnorePatterns: options.watchPathIgnorePatterns + }) +}); +const ensureNoDuplicateConfigs = (parsedConfigs, projects) => { + if (projects.length <= 1) { + return; + } + const configPathMap = new Map(); + for (const config of parsedConfigs) { + const {configPath} = config; + if (configPathMap.has(configPath)) { + const message = `Whoops! Two projects resolved to the same config path: ${_chalk().default.bold( + String(configPath) + )}: + + Project 1: ${_chalk().default.bold( + projects[parsedConfigs.findIndex(x => x === config)] + )} + Project 2: ${_chalk().default.bold( + projects[parsedConfigs.findIndex(x => x === configPathMap.get(configPath))] + )} + +This usually means that your ${_chalk().default.bold( + '"projects"' + )} config includes a directory that doesn't have any configuration recognizable by Jest. Please fix it. +`; + throw new Error(message); + } + if (configPath !== null) { + configPathMap.set(configPath, config); + } + } +}; +/** + * Reads the jest config, without validating them or filling it out with defaults. + * @param config The path to the file or serialized config. + * @param param1 Additional options + * @returns The raw initial config (not validated) + */ +async function readInitialOptions( + config, + { + packageRootOrConfig = process.cwd(), + parentConfigDirname = null, + readFromCwd = false, + skipMultipleConfigError = false + } = {} +) { + if (typeof packageRootOrConfig !== 'string') { + if (parentConfigDirname) { + const rawOptions = packageRootOrConfig; + rawOptions.rootDir = rawOptions.rootDir + ? (0, _utils.replaceRootDirInPath)( + parentConfigDirname, + rawOptions.rootDir + ) + : parentConfigDirname; + return { + config: rawOptions, + configPath: null + }; + } else { + throw new Error( + 'Jest: Cannot use configuration as an object without a file path.' + ); + } + } + if ((0, _utils.isJSONString)(config)) { + try { + // A JSON string was passed to `--config` argument and we can parse it + // and use as is. + const initialOptions = JSON.parse(config); + // NOTE: we might need to resolve this dir to an absolute path in the future + initialOptions.rootDir = initialOptions.rootDir || packageRootOrConfig; + return { + config: initialOptions, + configPath: null + }; + } catch { + throw new Error( + 'There was an error while parsing the `--config` argument as a JSON string.' + ); + } + } + if (!readFromCwd && typeof config == 'string') { + // A string passed to `--config`, which is either a direct path to the config + // or a path to directory containing `package.json`, `jest.config.js` or `jest.config.ts` + const configPath = (0, _resolveConfigPath.default)( + config, + process.cwd(), + skipMultipleConfigError + ); + return { + config: await (0, _readConfigFileAndSetRootDir.default)(configPath), + configPath + }; + } + // Otherwise just try to find config in the current rootDir. + const configPath = (0, _resolveConfigPath.default)( + packageRootOrConfig, + process.cwd(), + skipMultipleConfigError + ); + return { + config: await (0, _readConfigFileAndSetRootDir.default)(configPath), + configPath + }; +} + +// Possible scenarios: +// 1. jest --config config.json +// 2. jest --projects p1 p2 +// 3. jest --projects p1 p2 --config config.json +// 4. jest --projects p1 +// 5. jest +// +// If no projects are specified, process.cwd() will be used as the default +// (and only) project. +async function readConfigs(argv, projectPaths) { + let globalConfig; + let hasDeprecationWarnings; + let configs = []; + let projects = projectPaths; + let configPath; + if (projectPaths.length === 1) { + const parsedConfig = await readConfig(argv, projects[0]); + configPath = parsedConfig.configPath; + hasDeprecationWarnings = parsedConfig.hasDeprecationWarnings; + globalConfig = parsedConfig.globalConfig; + configs = [parsedConfig.projectConfig]; + if (globalConfig.projects && globalConfig.projects.length) { + // Even though we had one project in CLI args, there might be more + // projects defined in the config. + // In other words, if this was a single project, + // and its config has `projects` settings, use that value instead. + projects = globalConfig.projects; + } + } + if (projects.length > 0) { + const cwd = + process.platform === 'win32' + ? (0, _jestUtil().tryRealpath)(process.cwd()) + : process.cwd(); + const projectIsCwd = projects[0] === cwd; + const parsedConfigs = await Promise.all( + projects + .filter(root => { + // Ignore globbed files that cannot be `require`d. + if ( + typeof root === 'string' && + fs().existsSync(root) && + !fs().lstatSync(root).isDirectory() && + !constants.JEST_CONFIG_EXT_ORDER.some(ext => root.endsWith(ext)) + ) { + return false; + } + return true; + }) + .map((root, projectIndex) => { + const projectIsTheOnlyProject = + projectIndex === 0 && projects.length === 1; + const skipArgvConfigOption = !( + projectIsTheOnlyProject && projectIsCwd + ); + return readConfig( + argv, + root, + skipArgvConfigOption, + configPath ? path().dirname(configPath) : cwd, + projectIndex, + // we wanna skip the warning if this is the "main" project + projectIsCwd + ); + }) + ); + ensureNoDuplicateConfigs(parsedConfigs, projects); + configs = parsedConfigs.map(({projectConfig}) => projectConfig); + if (!hasDeprecationWarnings) { + hasDeprecationWarnings = parsedConfigs.some( + ({hasDeprecationWarnings}) => !!hasDeprecationWarnings + ); + } + // If no config was passed initially, use the one from the first project + if (!globalConfig) { + globalConfig = parsedConfigs[0].globalConfig; + } + } + if (!globalConfig || !configs.length) { + throw new Error('jest: No configuration found for any project.'); + } + return { + configs, + globalConfig, + hasDeprecationWarnings: !!hasDeprecationWarnings + }; +} diff --git a/node_modules/jest-config/build/normalize.js b/node_modules/jest-config/build/normalize.js new file mode 100644 index 0000000..9fa0cdb --- /dev/null +++ b/node_modules/jest-config/build/normalize.js @@ -0,0 +1,1172 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = normalize; +function _crypto() { + const data = require('crypto'); + _crypto = function () { + return data; + }; + return data; +} +function _os() { + const data = require('os'); + _os = function () { + return data; + }; + return data; +} +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _deepmerge() { + const data = _interopRequireDefault(require('deepmerge')); + _deepmerge = function () { + return data; + }; + return data; +} +function _glob() { + const data = require('glob'); + _glob = function () { + return data; + }; + return data; +} +function _gracefulFs() { + const data = require('graceful-fs'); + _gracefulFs = function () { + return data; + }; + return data; +} +function _micromatch() { + const data = _interopRequireDefault(require('micromatch')); + _micromatch = function () { + return data; + }; + return data; +} +function _jestRegexUtil() { + const data = require('jest-regex-util'); + _jestRegexUtil = function () { + return data; + }; + return data; +} +function _jestResolve() { + const data = _interopRequireWildcard(require('jest-resolve')); + _jestResolve = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _jestValidate() { + const data = require('jest-validate'); + _jestValidate = function () { + return data; + }; + return data; +} +var _Defaults = _interopRequireDefault(require('./Defaults')); +var _Deprecated = _interopRequireDefault(require('./Deprecated')); +var _ReporterValidationErrors = require('./ReporterValidationErrors'); +var _ValidConfig = _interopRequireDefault(require('./ValidConfig')); +var _color = require('./color'); +var _constants = require('./constants'); +var _getMaxWorkers = _interopRequireDefault(require('./getMaxWorkers')); +var _parseShardPair = require('./parseShardPair'); +var _setFromArgv = _interopRequireDefault(require('./setFromArgv')); +var _stringToBytes = _interopRequireDefault(require('./stringToBytes')); +var _utils = require('./utils'); +var _validatePattern = _interopRequireDefault(require('./validatePattern')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const ERROR = `${_utils.BULLET}Validation Error`; +const PRESET_EXTENSIONS = ['.json', '.js', '.cjs', '.mjs']; +const PRESET_NAME = 'jest-preset'; +const createConfigError = message => + new (_jestValidate().ValidationError)( + ERROR, + message, + _utils.DOCUMENTATION_NOTE + ); +function verifyDirectoryExists(path, key) { + try { + const rootStat = (0, _gracefulFs().statSync)(path); + if (!rootStat.isDirectory()) { + throw createConfigError( + ` ${_chalk().default.bold(path)} in the ${_chalk().default.bold( + key + )} option is not a directory.` + ); + } + } catch (err) { + if (err instanceof _jestValidate().ValidationError) { + throw err; + } + if (err.code === 'ENOENT') { + throw createConfigError( + ` Directory ${_chalk().default.bold( + path + )} in the ${_chalk().default.bold(key)} option was not found.` + ); + } + + // Not sure in which cases `statSync` can throw, so let's just show the underlying error to the user + throw createConfigError( + ` Got an error trying to find ${_chalk().default.bold( + path + )} in the ${_chalk().default.bold(key)} option.\n\n Error was: ${ + err.message + }` + ); + } +} +const mergeOptionWithPreset = (options, preset, optionName) => { + if (options[optionName] && preset[optionName]) { + options[optionName] = { + ...options[optionName], + ...preset[optionName], + ...options[optionName] + }; + } +}; +const mergeGlobalsWithPreset = (options, preset) => { + if (options.globals && preset.globals) { + options.globals = (0, _deepmerge().default)( + preset.globals, + options.globals + ); + } +}; +const setupPreset = async (options, optionsPreset) => { + let preset; + const presetPath = (0, _utils.replaceRootDirInPath)( + options.rootDir, + optionsPreset + ); + const presetModule = _jestResolve().default.findNodeModule( + presetPath.startsWith('.') + ? presetPath + : path().join(presetPath, PRESET_NAME), + { + basedir: options.rootDir, + extensions: PRESET_EXTENSIONS + } + ); + try { + if (!presetModule) { + throw new Error(`Cannot find module '${presetPath}'`); + } + + // Force re-evaluation to support multiple projects + try { + delete require.cache[require.resolve(presetModule)]; + } catch {} + preset = await (0, _jestUtil().requireOrImportModule)(presetModule); + } catch (error) { + if (error instanceof SyntaxError || error instanceof TypeError) { + throw createConfigError( + ` Preset ${_chalk().default.bold(presetPath)} is invalid:\n\n ${ + error.message + }\n ${error.stack}` + ); + } + if (error.message.includes('Cannot find module')) { + if (error.message.includes(presetPath)) { + const preset = _jestResolve().default.findNodeModule(presetPath, { + basedir: options.rootDir + }); + if (preset) { + throw createConfigError( + ` Module ${_chalk().default.bold( + presetPath + )} should have "jest-preset.js" or "jest-preset.json" file at the root.` + ); + } + throw createConfigError( + ` Preset ${_chalk().default.bold(presetPath)} not found.` + ); + } + throw createConfigError( + ` Missing dependency in ${_chalk().default.bold(presetPath)}:\n\n ${ + error.message + }\n ${error.stack}` + ); + } + throw createConfigError( + ` An unknown error occurred in ${_chalk().default.bold( + presetPath + )}:\n\n ${error.message}\n ${error.stack}` + ); + } + if (options.setupFiles) { + options.setupFiles = (preset.setupFiles || []).concat(options.setupFiles); + } + if (options.setupFilesAfterEnv) { + options.setupFilesAfterEnv = (preset.setupFilesAfterEnv || []).concat( + options.setupFilesAfterEnv + ); + } + if (options.modulePathIgnorePatterns && preset.modulePathIgnorePatterns) { + options.modulePathIgnorePatterns = preset.modulePathIgnorePatterns.concat( + options.modulePathIgnorePatterns + ); + } + mergeOptionWithPreset(options, preset, 'moduleNameMapper'); + mergeOptionWithPreset(options, preset, 'transform'); + mergeGlobalsWithPreset(options, preset); + return { + ...preset, + ...options + }; +}; +const setupBabelJest = options => { + const transform = options.transform; + let babelJest; + if (transform) { + const customJSPattern = Object.keys(transform).find(pattern => { + const regex = new RegExp(pattern); + return regex.test('a.js') || regex.test('a.jsx'); + }); + const customTSPattern = Object.keys(transform).find(pattern => { + const regex = new RegExp(pattern); + return regex.test('a.ts') || regex.test('a.tsx'); + }); + [customJSPattern, customTSPattern].forEach(pattern => { + if (pattern) { + const customTransformer = transform[pattern]; + if (Array.isArray(customTransformer)) { + if (customTransformer[0] === 'babel-jest') { + babelJest = require.resolve('babel-jest'); + customTransformer[0] = babelJest; + } else if (customTransformer[0].includes('babel-jest')) { + babelJest = customTransformer[0]; + } + } else { + if (customTransformer === 'babel-jest') { + babelJest = require.resolve('babel-jest'); + transform[pattern] = babelJest; + } else if (customTransformer.includes('babel-jest')) { + babelJest = customTransformer; + } + } + } + }); + } else { + babelJest = require.resolve('babel-jest'); + options.transform = { + [_constants.DEFAULT_JS_PATTERN]: babelJest + }; + } +}; +const normalizeCollectCoverageFrom = (options, key) => { + const initialCollectCoverageFrom = options[key]; + let value; + if (!initialCollectCoverageFrom) { + value = []; + } + if (!Array.isArray(initialCollectCoverageFrom)) { + try { + value = JSON.parse(initialCollectCoverageFrom); + } catch {} + if (options[key] && !Array.isArray(value)) { + value = [initialCollectCoverageFrom]; + } + } else { + value = initialCollectCoverageFrom; + } + if (value) { + value = value.map(filePath => + filePath.replace(/^(!?)(\/)(.*)/, '$1$3') + ); + } + return value; +}; +const normalizeUnmockedModulePathPatterns = (options, key) => + // _replaceRootDirTags is specifically well-suited for substituting + // in paths (it deals with properly interpreting relative path + // separators, etc). + // + // For patterns, direct global substitution is far more ideal, so we + // special case substitutions for patterns here. + options[key].map(pattern => + (0, _jestRegexUtil().replacePathSepForRegex)( + pattern.replace(//g, options.rootDir) + ) + ); +const normalizeMissingOptions = (options, configPath, projectIndex) => { + if (!options.id) { + options.id = (0, _crypto().createHash)('sha1') + .update(options.rootDir) + // In case we load config from some path that has the same root dir + .update(configPath || '') + .update(String(projectIndex)) + .digest('hex') + .substring(0, 32); + } + if (!options.setupFiles) { + options.setupFiles = []; + } + return options; +}; +const normalizeRootDir = options => { + // Assert that there *is* a rootDir + if (!options.rootDir) { + throw createConfigError( + ` Configuration option ${_chalk().default.bold( + 'rootDir' + )} must be specified.` + ); + } + options.rootDir = path().normalize(options.rootDir); + try { + // try to resolve windows short paths, ignoring errors (permission errors, mostly) + options.rootDir = (0, _jestUtil().tryRealpath)(options.rootDir); + } catch { + // ignored + } + verifyDirectoryExists(options.rootDir, 'rootDir'); + return { + ...options, + rootDir: options.rootDir + }; +}; +const normalizeReporters = ({reporters, rootDir}) => { + if (!reporters || !Array.isArray(reporters)) { + return undefined; + } + (0, _ReporterValidationErrors.validateReporters)(reporters); + return reporters.map(reporterConfig => { + const normalizedReporterConfig = + typeof reporterConfig === 'string' + ? // if reporter config is a string, we wrap it in an array + // and pass an empty object for options argument, to normalize + // the shape. + [reporterConfig, {}] + : reporterConfig; + const reporterPath = (0, _utils.replaceRootDirInPath)( + rootDir, + normalizedReporterConfig[0] + ); + if (!['default', 'github-actions', 'summary'].includes(reporterPath)) { + const reporter = _jestResolve().default.findNodeModule(reporterPath, { + basedir: rootDir + }); + if (!reporter) { + throw new (_jestResolve().default.ModuleNotFoundError)( + 'Could not resolve a module for a custom reporter.\n' + + ` Module name: ${reporterPath}` + ); + } + normalizedReporterConfig[0] = reporter; + } + return normalizedReporterConfig; + }); +}; +const buildTestPathPattern = argv => { + const patterns = []; + if (argv._) { + patterns.push(...argv._); + } + if (argv.testPathPattern) { + patterns.push(...argv.testPathPattern); + } + const replacePosixSep = pattern => { + // yargs coerces positional args into numbers + const patternAsString = pattern.toString(); + if (path().sep === '/') { + return patternAsString; + } + return patternAsString.replace(/\//g, '\\\\'); + }; + const testPathPattern = patterns.map(replacePosixSep).join('|'); + if ((0, _validatePattern.default)(testPathPattern)) { + return testPathPattern; + } else { + showTestPathPatternError(testPathPattern); + return ''; + } +}; +const showTestPathPatternError = testPathPattern => { + (0, _jestUtil().clearLine)(process.stdout); + + // eslint-disable-next-line no-console + console.log( + _chalk().default.red( + ` Invalid testPattern ${testPathPattern} supplied. ` + + 'Running all tests instead.' + ) + ); +}; +function validateExtensionsToTreatAsEsm(extensionsToTreatAsEsm) { + if (!extensionsToTreatAsEsm || extensionsToTreatAsEsm.length === 0) { + return; + } + function printConfig(opts) { + const string = opts.map(ext => `'${ext}'`).join(', '); + return _chalk().default.bold(`extensionsToTreatAsEsm: [${string}]`); + } + const extensionWithoutDot = extensionsToTreatAsEsm.some( + ext => !ext.startsWith('.') + ); + if (extensionWithoutDot) { + throw createConfigError(` Option: ${printConfig( + extensionsToTreatAsEsm + )} includes a string that does not start with a period (${_chalk().default.bold( + '.' + )}). + Please change your configuration to ${printConfig( + extensionsToTreatAsEsm.map(ext => (ext.startsWith('.') ? ext : `.${ext}`)) + )}.`); + } + if (extensionsToTreatAsEsm.includes('.js')) { + throw createConfigError( + ` Option: ${printConfig( + extensionsToTreatAsEsm + )} includes ${_chalk().default.bold( + "'.js'" + )} which is always inferred based on ${_chalk().default.bold( + 'type' + )} in its nearest ${_chalk().default.bold('package.json')}.` + ); + } + if (extensionsToTreatAsEsm.includes('.cjs')) { + throw createConfigError( + ` Option: ${printConfig( + extensionsToTreatAsEsm + )} includes ${_chalk().default.bold( + "'.cjs'" + )} which is always treated as CommonJS.` + ); + } + if (extensionsToTreatAsEsm.includes('.mjs')) { + throw createConfigError( + ` Option: ${printConfig( + extensionsToTreatAsEsm + )} includes ${_chalk().default.bold( + "'.mjs'" + )} which is always treated as an ECMAScript Module.` + ); + } +} +async function normalize( + initialOptions, + argv, + configPath, + projectIndex = Infinity +) { + const {hasDeprecationWarnings} = (0, _jestValidate().validate)( + initialOptions, + { + comment: _utils.DOCUMENTATION_NOTE, + deprecatedConfig: _Deprecated.default, + exampleConfig: _ValidConfig.default, + recursiveDenylist: [ + // 'coverageThreshold' allows to use 'global' and glob strings on the same + // level, there's currently no way we can deal with such config + 'coverageThreshold', + 'globals', + 'moduleNameMapper', + 'testEnvironmentOptions', + 'transform' + ] + } + ); + let options = normalizeMissingOptions( + normalizeRootDir((0, _setFromArgv.default)(initialOptions, argv)), + configPath, + projectIndex + ); + if (options.preset) { + options = await setupPreset(options, options.preset); + } + if (!options.setupFilesAfterEnv) { + options.setupFilesAfterEnv = []; + } + options.testEnvironment = (0, _jestResolve().resolveTestEnvironment)({ + requireResolveFunction: require.resolve, + rootDir: options.rootDir, + testEnvironment: + options.testEnvironment || + require.resolve(_Defaults.default.testEnvironment) + }); + if (!options.roots) { + options.roots = [options.rootDir]; + } + if ( + !options.testRunner || + options.testRunner === 'circus' || + options.testRunner === 'jest-circus' || + options.testRunner === 'jest-circus/runner' + ) { + options.testRunner = require.resolve('jest-circus/runner'); + } else if (options.testRunner === 'jasmine2') { + try { + options.testRunner = require.resolve('jest-jasmine2'); + } catch (error) { + if (error.code === 'MODULE_NOT_FOUND') { + throw createConfigError( + 'jest-jasmine is no longer shipped by default with Jest, you need to install it explicitly or provide an absolute path to Jest' + ); + } + throw error; + } + } + if (!options.coverageDirectory) { + options.coverageDirectory = path().resolve(options.rootDir, 'coverage'); + } + setupBabelJest(options); + // TODO: Type this properly + const newOptions = { + ..._Defaults.default + }; + if (options.resolver) { + newOptions.resolver = (0, _utils.resolve)(null, { + filePath: options.resolver, + key: 'resolver', + rootDir: options.rootDir + }); + } + validateExtensionsToTreatAsEsm(options.extensionsToTreatAsEsm); + if (options.watchman == null) { + options.watchman = _Defaults.default.watchman; + } + const optionKeys = Object.keys(options); + optionKeys.reduce((newOptions, key) => { + // The resolver has been resolved separately; skip it + if (key === 'resolver') { + return newOptions; + } + + // This is cheating, because it claims that all keys of InitialOptions are Required. + // We only really know it's Required for oldOptions[key], not for oldOptions.someOtherKey, + // so oldOptions[key] is the only way it should be used. + const oldOptions = options; + let value; + switch (key) { + case 'setupFiles': + case 'setupFilesAfterEnv': + case 'snapshotSerializers': + { + const option = oldOptions[key]; + value = + option && + option.map(filePath => + (0, _utils.resolve)(newOptions.resolver, { + filePath, + key, + rootDir: options.rootDir + }) + ); + } + break; + case 'modulePaths': + case 'roots': + { + const option = oldOptions[key]; + value = + option && + option.map(filePath => + path().resolve( + options.rootDir, + (0, _utils.replaceRootDirInPath)(options.rootDir, filePath) + ) + ); + } + break; + case 'collectCoverageFrom': + value = normalizeCollectCoverageFrom(oldOptions, key); + break; + case 'cacheDirectory': + case 'coverageDirectory': + { + const option = oldOptions[key]; + value = + option && + path().resolve( + options.rootDir, + (0, _utils.replaceRootDirInPath)(options.rootDir, option) + ); + } + break; + case 'dependencyExtractor': + case 'globalSetup': + case 'globalTeardown': + case 'runtime': + case 'snapshotResolver': + case 'testResultsProcessor': + case 'testRunner': + case 'filter': + { + const option = oldOptions[key]; + value = + option && + (0, _utils.resolve)(newOptions.resolver, { + filePath: option, + key, + rootDir: options.rootDir + }); + } + break; + case 'runner': + { + const option = oldOptions[key]; + value = + option && + (0, _jestResolve().resolveRunner)(newOptions.resolver, { + filePath: option, + requireResolveFunction: require.resolve, + rootDir: options.rootDir + }); + } + break; + case 'prettierPath': + { + // We only want this to throw if "prettierPath" is explicitly passed + // from config or CLI, and the requested path isn't found. Otherwise we + // set it to null and throw an error lazily when it is used. + + const option = oldOptions[key]; + value = + option && + (0, _utils.resolve)(newOptions.resolver, { + filePath: option, + key, + optional: option === _Defaults.default[key], + rootDir: options.rootDir + }); + } + break; + case 'moduleNameMapper': + const moduleNameMapper = oldOptions[key]; + value = + moduleNameMapper && + Object.keys(moduleNameMapper).map(regex => { + const item = moduleNameMapper && moduleNameMapper[regex]; + return ( + item && [ + regex, + (0, _utils._replaceRootDirTags)(options.rootDir, item) + ] + ); + }); + break; + case 'transform': + const transform = oldOptions[key]; + value = + transform && + Object.keys(transform).map(regex => { + const transformElement = transform[regex]; + return [ + regex, + (0, _utils.resolve)(newOptions.resolver, { + filePath: Array.isArray(transformElement) + ? transformElement[0] + : transformElement, + key, + rootDir: options.rootDir + }), + Array.isArray(transformElement) ? transformElement[1] : {} + ]; + }); + break; + case 'reporters': + value = normalizeReporters(oldOptions); + break; + case 'coveragePathIgnorePatterns': + case 'modulePathIgnorePatterns': + case 'testPathIgnorePatterns': + case 'transformIgnorePatterns': + case 'watchPathIgnorePatterns': + case 'unmockedModulePathPatterns': + value = normalizeUnmockedModulePathPatterns(oldOptions, key); + break; + case 'haste': + value = { + ...oldOptions[key] + }; + if (value.hasteImplModulePath != null) { + const resolvedHasteImpl = (0, _utils.resolve)(newOptions.resolver, { + filePath: (0, _utils.replaceRootDirInPath)( + options.rootDir, + value.hasteImplModulePath + ), + key: 'haste.hasteImplModulePath', + rootDir: options.rootDir + }); + value.hasteImplModulePath = resolvedHasteImpl || undefined; + } + break; + case 'projects': + value = (oldOptions[key] || []) + .map(project => + typeof project === 'string' + ? (0, _utils._replaceRootDirTags)(options.rootDir, project) + : project + ) + .reduce((projects, project) => { + // Project can be specified as globs. If a glob matches any files, + // We expand it to these paths. If not, we keep the original path + // for the future resolution. + const globMatches = + typeof project === 'string' ? (0, _glob().sync)(project) : []; + return projects.concat(globMatches.length ? globMatches : project); + }, []); + break; + case 'moduleDirectories': + case 'testMatch': + { + const replacedRootDirTags = (0, _utils._replaceRootDirTags)( + (0, _utils.escapeGlobCharacters)(options.rootDir), + oldOptions[key] + ); + if (replacedRootDirTags) { + value = Array.isArray(replacedRootDirTags) + ? replacedRootDirTags.map(_jestUtil().replacePathSepForGlob) + : (0, _jestUtil().replacePathSepForGlob)(replacedRootDirTags); + } else { + value = replacedRootDirTags; + } + } + break; + case 'testRegex': + { + const option = oldOptions[key]; + value = option + ? (Array.isArray(option) ? option : [option]).map( + _jestRegexUtil().replacePathSepForRegex + ) + : []; + } + break; + case 'moduleFileExtensions': { + value = oldOptions[key]; + if ( + Array.isArray(value) && + // If it's the wrong type, it can throw at a later time + (options.runner === undefined || + options.runner === _Defaults.default.runner) && + // Only require 'js' for the default jest-runner + !value.includes('js') + ) { + const errorMessage = + " moduleFileExtensions must include 'js':\n" + + ' but instead received:\n' + + ` ${_chalk().default.bold.red(JSON.stringify(value))}`; + + // If `js` is not included, any dependency Jest itself injects into + // the environment, like jasmine or sourcemap-support, will need to + // `require` its modules with a file extension. This is not plausible + // in the long run, so it's way easier to just fail hard early. + // We might consider throwing if `json` is missing as well, as it's a + // fair assumption from modules that they can do + // `require('some-package/package') without the trailing `.json` as it + // works in Node normally. + throw createConfigError( + `${errorMessage}\n Please change your configuration to include 'js'.` + ); + } + break; + } + case 'bail': { + const bail = oldOptions[key]; + if (typeof bail === 'boolean') { + value = bail ? 1 : 0; + } else if (typeof bail === 'string') { + value = 1; + // If Jest is invoked as `jest --bail someTestPattern` then need to + // move the pattern from the `bail` configuration and into `argv._` + // to be processed as an extra parameter + argv._.push(bail); + } else { + value = oldOptions[key]; + } + break; + } + case 'displayName': { + const displayName = oldOptions[key]; + /** + * Ensuring that displayName shape is correct here so that the + * reporters can trust the shape of the data + */ + if (typeof displayName === 'object') { + const {name, color} = displayName; + if ( + !name || + !color || + typeof name !== 'string' || + typeof color !== 'string' + ) { + const errorMessage = + ` Option "${_chalk().default.bold( + 'displayName' + )}" must be of type:\n\n` + + ' {\n' + + ' name: string;\n' + + ' color: string;\n' + + ' }\n'; + throw createConfigError(errorMessage); + } + value = oldOptions[key]; + } else { + value = { + color: (0, _color.getDisplayNameColor)(options.runner), + name: displayName + }; + } + break; + } + case 'testTimeout': { + if (oldOptions[key] < 0) { + throw createConfigError( + ` Option "${_chalk().default.bold( + 'testTimeout' + )}" must be a natural number.` + ); + } + value = oldOptions[key]; + break; + } + case 'snapshotFormat': { + value = { + ..._Defaults.default.snapshotFormat, + ...oldOptions[key] + }; + break; + } + case 'automock': + case 'cache': + case 'changedSince': + case 'changedFilesWithAncestor': + case 'clearMocks': + case 'collectCoverage': + case 'coverageProvider': + case 'coverageReporters': + case 'coverageThreshold': + case 'detectLeaks': + case 'detectOpenHandles': + case 'errorOnDeprecated': + case 'expand': + case 'extensionsToTreatAsEsm': + case 'globals': + case 'fakeTimers': + case 'findRelatedTests': + case 'forceCoverageMatch': + case 'forceExit': + case 'injectGlobals': + case 'lastCommit': + case 'listTests': + case 'logHeapUsage': + case 'maxConcurrency': + case 'id': + case 'noStackTrace': + case 'notify': + case 'notifyMode': + case 'onlyChanged': + case 'onlyFailures': + case 'outputFile': + case 'passWithNoTests': + case 'replname': + case 'resetMocks': + case 'resetModules': + case 'restoreMocks': + case 'rootDir': + case 'runTestsByPath': + case 'sandboxInjectedGlobals': + case 'silent': + case 'showSeed': + case 'skipFilter': + case 'skipNodeResolution': + case 'slowTestThreshold': + case 'testEnvironment': + case 'testEnvironmentOptions': + case 'testFailureExitCode': + case 'testLocationInResults': + case 'testNamePattern': + case 'useStderr': + case 'verbose': + case 'watch': + case 'watchAll': + case 'watchman': + value = oldOptions[key]; + break; + case 'workerIdleMemoryLimit': + value = (0, _stringToBytes.default)( + oldOptions[key], + (0, _os().totalmem)() + ); + break; + case 'watchPlugins': + value = (oldOptions[key] || []).map(watchPlugin => { + if (typeof watchPlugin === 'string') { + return { + config: {}, + path: (0, _jestResolve().resolveWatchPlugin)( + newOptions.resolver, + { + filePath: watchPlugin, + requireResolveFunction: require.resolve, + rootDir: options.rootDir + } + ) + }; + } else { + return { + config: watchPlugin[1] || {}, + path: (0, _jestResolve().resolveWatchPlugin)( + newOptions.resolver, + { + filePath: watchPlugin[0], + requireResolveFunction: require.resolve, + rootDir: options.rootDir + } + ) + }; + } + }); + break; + } + // @ts-expect-error: automock is missing in GlobalConfig, so what + newOptions[key] = value; + return newOptions; + }, newOptions); + if (options.watchman && options.haste?.enableSymlinks) { + throw new (_jestValidate().ValidationError)( + 'Validation Error', + 'haste.enableSymlinks is incompatible with watchman', + 'Either set haste.enableSymlinks to false or do not use watchman' + ); + } + newOptions.roots.forEach((root, i) => { + verifyDirectoryExists(root, `roots[${i}]`); + }); + try { + // try to resolve windows short paths, ignoring errors (permission errors, mostly) + newOptions.cwd = (0, _jestUtil().tryRealpath)(process.cwd()); + } catch { + // ignored + } + newOptions.testSequencer = (0, _jestResolve().resolveSequencer)( + newOptions.resolver, + { + filePath: + options.testSequencer || + require.resolve(_Defaults.default.testSequencer), + requireResolveFunction: require.resolve, + rootDir: options.rootDir + } + ); + if (newOptions.runner === _Defaults.default.runner) { + newOptions.runner = require.resolve(newOptions.runner); + } + newOptions.nonFlagArgs = argv._?.map(arg => `${arg}`); + newOptions.testPathPattern = buildTestPathPattern(argv); + newOptions.json = !!argv.json; + newOptions.testFailureExitCode = parseInt(newOptions.testFailureExitCode, 10); + if ( + newOptions.lastCommit || + newOptions.changedFilesWithAncestor || + newOptions.changedSince + ) { + newOptions.onlyChanged = true; + } + if (argv.all) { + newOptions.onlyChanged = false; + newOptions.onlyFailures = false; + } else if (newOptions.testPathPattern) { + // When passing a test path pattern we don't want to only monitor changed + // files unless `--watch` is also passed. + newOptions.onlyChanged = newOptions.watch; + } + newOptions.showSeed = newOptions.showSeed || argv.showSeed; + const upperBoundSeedValue = 2 ** 31; + + // xoroshiro128plus is used in v8 and is used here (at time of writing) + newOptions.seed = + argv.seed ?? + Math.floor((2 ** 32 - 1) * Math.random() - upperBoundSeedValue); + if ( + newOptions.seed < -upperBoundSeedValue || + newOptions.seed > upperBoundSeedValue - 1 + ) { + throw new (_jestValidate().ValidationError)( + 'Validation Error', + `seed value must be between \`-0x80000000\` and \`0x7fffffff\` inclusive - is ${newOptions.seed}` + ); + } + if (!newOptions.onlyChanged) { + newOptions.onlyChanged = false; + } + if (!newOptions.lastCommit) { + newOptions.lastCommit = false; + } + if (!newOptions.onlyFailures) { + newOptions.onlyFailures = false; + } + if (!newOptions.watchAll) { + newOptions.watchAll = false; + } + + // as unknown since it can happen. We really need to fix the types here + if (newOptions.moduleNameMapper === _Defaults.default.moduleNameMapper) { + newOptions.moduleNameMapper = []; + } + if (argv.ci != null) { + newOptions.ci = argv.ci; + } + newOptions.updateSnapshot = + newOptions.ci && !argv.updateSnapshot + ? 'none' + : argv.updateSnapshot + ? 'all' + : 'new'; + newOptions.maxConcurrency = parseInt(newOptions.maxConcurrency, 10); + newOptions.maxWorkers = (0, _getMaxWorkers.default)(argv, options); + if (newOptions.testRegex.length > 0 && options.testMatch) { + throw createConfigError( + ` Configuration options ${_chalk().default.bold('testMatch')} and` + + ` ${_chalk().default.bold('testRegex')} cannot be used together.` + ); + } + if (newOptions.testRegex.length > 0 && !options.testMatch) { + // Prevent the default testMatch conflicting with any explicitly + // configured `testRegex` value + newOptions.testMatch = []; + } + + // If argv.json is set, coverageReporters shouldn't print a text report. + if (argv.json) { + newOptions.coverageReporters = (newOptions.coverageReporters || []).filter( + reporter => reporter !== 'text' + ); + } + + // If collectCoverage is enabled while using --findRelatedTests we need to + // avoid having false negatives in the generated coverage report. + // The following: `--findRelatedTests '/rootDir/file1.js' --coverage` + // Is transformed to: `--findRelatedTests '/rootDir/file1.js' --coverage --collectCoverageFrom 'file1.js'` + // where arguments to `--collectCoverageFrom` should be globs (or relative + // paths to the rootDir) + if (newOptions.collectCoverage && argv.findRelatedTests) { + let collectCoverageFrom = newOptions.nonFlagArgs.map(filename => { + filename = (0, _utils.replaceRootDirInPath)(options.rootDir, filename); + return path().isAbsolute(filename) + ? path().relative(options.rootDir, filename) + : filename; + }); + + // Don't override existing collectCoverageFrom options + if (newOptions.collectCoverageFrom) { + collectCoverageFrom = collectCoverageFrom.reduce((patterns, filename) => { + if ( + (0, _micromatch().default)( + [ + (0, _jestUtil().replacePathSepForGlob)( + path().relative(options.rootDir, filename) + ) + ], + newOptions.collectCoverageFrom + ).length === 0 + ) { + return patterns; + } + return [...patterns, filename]; + }, newOptions.collectCoverageFrom); + } + newOptions.collectCoverageFrom = collectCoverageFrom; + } else if (!newOptions.collectCoverageFrom) { + newOptions.collectCoverageFrom = []; + } + if (!newOptions.findRelatedTests) { + newOptions.findRelatedTests = false; + } + if (!newOptions.projects) { + newOptions.projects = []; + } + if (!newOptions.sandboxInjectedGlobals) { + newOptions.sandboxInjectedGlobals = []; + } + if (!newOptions.forceExit) { + newOptions.forceExit = false; + } + if (!newOptions.logHeapUsage) { + newOptions.logHeapUsage = false; + } + if (argv.shard) { + newOptions.shard = (0, _parseShardPair.parseShardPair)(argv.shard); + } + return { + hasDeprecationWarnings, + options: newOptions + }; +} diff --git a/node_modules/jest-config/build/parseShardPair.js b/node_modules/jest-config/build/parseShardPair.js new file mode 100644 index 0000000..443c7e8 --- /dev/null +++ b/node_modules/jest-config/build/parseShardPair.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.parseShardPair = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const parseShardPair = pair => { + const shardPair = pair + .split('/') + .filter(d => /^\d+$/.test(d)) + .map(d => parseInt(d, 10)) + .filter(shard => !Number.isNaN(shard)); + const [shardIndex, shardCount] = shardPair; + if (shardPair.length !== 2) { + throw new Error( + 'The shard option requires a string in the format of /.' + ); + } + if (shardIndex === 0 || shardCount === 0) { + throw new Error( + 'The shard option requires 1-based values, received 0 or lower in the pair.' + ); + } + if (shardIndex > shardCount) { + throw new Error( + 'The shard option / requires to be lower or equal than .' + ); + } + return { + shardCount, + shardIndex + }; +}; +exports.parseShardPair = parseShardPair; diff --git a/node_modules/jest-config/build/readConfigFileAndSetRootDir.js b/node_modules/jest-config/build/readConfigFileAndSetRootDir.js new file mode 100644 index 0000000..97a88bc --- /dev/null +++ b/node_modules/jest-config/build/readConfigFileAndSetRootDir.js @@ -0,0 +1,189 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = readConfigFileAndSetRootDir; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _parseJson() { + const data = _interopRequireDefault(require('parse-json')); + _parseJson = function () { + return data; + }; + return data; +} +function _stripJsonComments() { + const data = _interopRequireDefault(require('strip-json-comments')); + _stripJsonComments = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _constants = require('./constants'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Read the configuration and set its `rootDir` +// 1. If it's a `package.json` file, we look into its "jest" property +// 2. If it's a `jest.config.ts` file, we use `ts-node` to transpile & require it +// 3. For any other file, we just require it. If we receive an 'ERR_REQUIRE_ESM' +// from node, perform a dynamic import instead. +async function readConfigFileAndSetRootDir(configPath) { + const isTS = configPath.endsWith(_constants.JEST_CONFIG_EXT_TS); + const isJSON = configPath.endsWith(_constants.JEST_CONFIG_EXT_JSON); + let configObject; + try { + if (isTS) { + configObject = await loadTSConfigFile(configPath); + } else if (isJSON) { + const fileContent = fs().readFileSync(configPath, 'utf8'); + configObject = (0, _parseJson().default)( + (0, _stripJsonComments().default)(fileContent), + configPath + ); + } else { + configObject = await (0, _jestUtil().requireOrImportModule)(configPath); + } + } catch (error) { + if (isTS) { + throw new Error( + `Jest: Failed to parse the TypeScript config file ${configPath}\n` + + ` ${error}` + ); + } + throw error; + } + if (configPath.endsWith(_constants.PACKAGE_JSON)) { + // Event if there's no "jest" property in package.json we will still use + // an empty object. + configObject = configObject.jest || {}; + } + if (typeof configObject === 'function') { + configObject = await configObject(); + } + if (configObject.rootDir) { + // We don't touch it if it has an absolute path specified + if (!path().isAbsolute(configObject.rootDir)) { + // otherwise, we'll resolve it relative to the file's __dirname + configObject.rootDir = path().resolve( + path().dirname(configPath), + configObject.rootDir + ); + } + } else { + // If rootDir is not there, we'll set it to this file's __dirname + configObject.rootDir = path().dirname(configPath); + } + return configObject; +} + +// Load the TypeScript configuration +const loadTSConfigFile = async configPath => { + // Get registered TypeScript compiler instance + const registeredCompiler = await getRegisteredCompiler(); + registeredCompiler.enabled(true); + let configObject = (0, _jestUtil().interopRequireDefault)( + require(configPath) + ).default; + + // In case the config is a function which imports more Typescript code + if (typeof configObject === 'function') { + configObject = await configObject(); + } + registeredCompiler.enabled(false); + return configObject; +}; +let registeredCompilerPromise; +function getRegisteredCompiler() { + // Cache the promise to avoid multiple registrations + registeredCompilerPromise = registeredCompilerPromise ?? registerTsNode(); + return registeredCompilerPromise; +} +async function registerTsNode() { + try { + // Register TypeScript compiler instance + const tsNode = await import('ts-node'); + return tsNode.register({ + compilerOptions: { + module: 'CommonJS' + }, + moduleTypes: { + '**': 'cjs' + } + }); + } catch (e) { + if (e.code === 'ERR_MODULE_NOT_FOUND') { + throw new Error( + `Jest: 'ts-node' is required for the TypeScript configuration files. Make sure it is installed\nError: ${e.message}` + ); + } + throw e; + } +} diff --git a/node_modules/jest-config/build/resolveConfigPath.js b/node_modules/jest-config/build/resolveConfigPath.js new file mode 100644 index 0000000..a1c5e92 --- /dev/null +++ b/node_modules/jest-config/build/resolveConfigPath.js @@ -0,0 +1,217 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = resolveConfigPath; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _slash() { + const data = _interopRequireDefault(require('slash')); + _slash = function () { + return data; + }; + return data; +} +function _jestValidate() { + const data = require('jest-validate'); + _jestValidate = function () { + return data; + }; + return data; +} +var _constants = require('./constants'); +var _utils = require('./utils'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const isFile = filePath => + fs().existsSync(filePath) && !fs().lstatSync(filePath).isDirectory(); +const getConfigFilename = ext => _constants.JEST_CONFIG_BASE_NAME + ext; +function resolveConfigPath( + pathToResolve, + cwd, + skipMultipleConfigError = false +) { + if (!path().isAbsolute(cwd)) { + throw new Error(`"cwd" must be an absolute path. cwd: ${cwd}`); + } + const absolutePath = path().isAbsolute(pathToResolve) + ? pathToResolve + : path().resolve(cwd, pathToResolve); + if (isFile(absolutePath)) { + return absolutePath; + } + + // This is a guard against passing non existing path as a project/config, + // that will otherwise result in a very confusing situation. + // e.g. + // With a directory structure like this: + // my_project/ + // package.json + // + // Passing a `my_project/some_directory_that_doesnt_exist` as a project + // name will resolve into a (possibly empty) `my_project/package.json` and + // try to run all tests it finds under `my_project` directory. + if (!fs().existsSync(absolutePath)) { + throw new Error( + "Can't find a root directory while resolving a config file path.\n" + + `Provided path to resolve: ${pathToResolve}\n` + + `cwd: ${cwd}` + ); + } + return resolveConfigPathByTraversing( + absolutePath, + pathToResolve, + cwd, + skipMultipleConfigError + ); +} +const resolveConfigPathByTraversing = ( + pathToResolve, + initialPath, + cwd, + skipMultipleConfigError +) => { + const configFiles = _constants.JEST_CONFIG_EXT_ORDER.map(ext => + path().resolve(pathToResolve, getConfigFilename(ext)) + ).filter(isFile); + const packageJson = findPackageJson(pathToResolve); + if (packageJson && hasPackageJsonJestKey(packageJson)) { + configFiles.push(packageJson); + } + if (!skipMultipleConfigError && configFiles.length > 1) { + throw new (_jestValidate().ValidationError)( + ...makeMultipleConfigsErrorMessage(configFiles) + ); + } + if (configFiles.length > 0 || packageJson) { + return configFiles[0] ?? packageJson; + } + + // This is the system root. + // We tried everything, config is nowhere to be found ¯\_(ツ)_/¯ + if (pathToResolve === path().dirname(pathToResolve)) { + throw new Error(makeResolutionErrorMessage(initialPath, cwd)); + } + + // go up a level and try it again + return resolveConfigPathByTraversing( + path().dirname(pathToResolve), + initialPath, + cwd, + skipMultipleConfigError + ); +}; +const findPackageJson = pathToResolve => { + const packagePath = path().resolve(pathToResolve, _constants.PACKAGE_JSON); + if (isFile(packagePath)) { + return packagePath; + } + return undefined; +}; +const hasPackageJsonJestKey = packagePath => { + const content = fs().readFileSync(packagePath, 'utf8'); + try { + return 'jest' in JSON.parse(content); + } catch { + // If package is not a valid JSON + return false; + } +}; +const makeResolutionErrorMessage = (initialPath, cwd) => + 'Could not find a config file based on provided values:\n' + + `path: "${initialPath}"\n` + + `cwd: "${cwd}"\n` + + 'Config paths must be specified by either a direct path to a config\n' + + 'file, or a path to a directory. If directory is given, Jest will try to\n' + + `traverse directory tree up, until it finds one of those files in exact order: ${_constants.JEST_CONFIG_EXT_ORDER.map( + ext => `"${getConfigFilename(ext)}"` + ).join(' or ')}.`; +function extraIfPackageJson(configPath) { + if (configPath.endsWith(_constants.PACKAGE_JSON)) { + return '`jest` key in '; + } + return ''; +} +const makeMultipleConfigsErrorMessage = configPaths => [ + `${_utils.BULLET}${_chalk().default.bold('Multiple configurations found')}`, + [ + ...configPaths.map( + configPath => + ` * ${extraIfPackageJson(configPath)}${(0, _slash().default)( + configPath + )}` + ), + '', + ' Implicit config resolution does not allow multiple configuration files.', + ' Either remove unused config files or select one explicitly with `--config`.' + ].join('\n'), + _utils.DOCUMENTATION_NOTE +]; diff --git a/node_modules/jest-config/build/setFromArgv.js b/node_modules/jest-config/build/setFromArgv.js new file mode 100644 index 0000000..9e6fa02 --- /dev/null +++ b/node_modules/jest-config/build/setFromArgv.js @@ -0,0 +1,57 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = setFromArgv; +var _utils = require('./utils'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const specialArgs = ['_', '$0', 'h', 'help', 'config']; +function setFromArgv(options, argv) { + const argvToOptions = Object.keys(argv) + .filter(key => argv[key] !== undefined && specialArgs.indexOf(key) === -1) + .reduce((options, key) => { + switch (key) { + case 'coverage': + options.collectCoverage = argv[key]; + break; + case 'json': + options.useStderr = argv[key]; + break; + case 'watchAll': + options.watch = false; + options.watchAll = argv[key]; + break; + case 'env': + options.testEnvironment = argv[key]; + break; + case 'config': + break; + case 'coverageThreshold': + case 'globals': + case 'haste': + case 'moduleNameMapper': + case 'testEnvironmentOptions': + case 'transform': + const str = argv[key]; + if ((0, _utils.isJSONString)(str)) { + options[key] = JSON.parse(str); + } + break; + default: + options[key] = argv[key]; + } + return options; + }, {}); + return { + ...options, + ...((0, _utils.isJSONString)(argv.config) ? JSON.parse(argv.config) : null), + ...argvToOptions + }; +} diff --git a/node_modules/jest-config/build/stringToBytes.js b/node_modules/jest-config/build/stringToBytes.js new file mode 100644 index 0000000..99b4f47 --- /dev/null +++ b/node_modules/jest-config/build/stringToBytes.js @@ -0,0 +1,79 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Converts a string representing an amount of memory to bytes. + * + * @param input The value to convert to bytes. + * @param percentageReference The reference value to use when a '%' value is supplied. + */ +function stringToBytes(input, percentageReference) { + if (input === null || input === undefined) { + return input; + } + if (typeof input === 'string') { + if (isNaN(Number.parseFloat(input.slice(-1)))) { + // eslint-disable-next-line prefer-const + let [, numericString, trailingChars] = + input.match(/(.*?)([^0-9.-]+)$/i) || []; + if (trailingChars && numericString) { + const numericValue = Number.parseFloat(numericString); + trailingChars = trailingChars.toLowerCase(); + switch (trailingChars) { + case '%': + input = numericValue / 100; + break; + case 'kb': + case 'k': + return numericValue * 1000; + case 'kib': + return numericValue * 1024; + case 'mb': + case 'm': + return numericValue * 1000 * 1000; + case 'mib': + return numericValue * 1024 * 1024; + case 'gb': + case 'g': + return numericValue * 1000 * 1000 * 1000; + case 'gib': + return numericValue * 1024 * 1024 * 1024; + } + } + + // It ends in some kind of char so we need to do some parsing + } else { + input = Number.parseFloat(input); + } + } + if (typeof input === 'number') { + if (input <= 1 && input > 0) { + if (percentageReference) { + return Math.floor(input * percentageReference); + } else { + throw new Error( + 'For a percentage based memory limit a percentageReference must be supplied' + ); + } + } else if (input > 1) { + return Math.floor(input); + } else { + throw new Error('Unexpected numerical input'); + } + } + throw new Error('Unexpected input'); +} + +// https://github.com/import-js/eslint-plugin-import/issues/1590 +var _default = stringToBytes; +exports.default = _default; diff --git a/node_modules/jest-config/build/utils.js b/node_modules/jest-config/build/utils.js new file mode 100644 index 0000000..36bba2e --- /dev/null +++ b/node_modules/jest-config/build/utils.js @@ -0,0 +1,172 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.resolve = + exports.replaceRootDirInPath = + exports.isJSONString = + exports.escapeGlobCharacters = + exports._replaceRootDirTags = + exports.DOCUMENTATION_NOTE = + exports.BULLET = + void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestResolve() { + const data = _interopRequireDefault(require('jest-resolve')); + _jestResolve = function () { + return data; + }; + return data; +} +function _jestValidate() { + const data = require('jest-validate'); + _jestValidate = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const BULLET = _chalk().default.bold('\u25cf '); +exports.BULLET = BULLET; +const DOCUMENTATION_NOTE = ` ${_chalk().default.bold( + 'Configuration Documentation:' +)} + https://jestjs.io/docs/configuration +`; +exports.DOCUMENTATION_NOTE = DOCUMENTATION_NOTE; +const createValidationError = message => + new (_jestValidate().ValidationError)( + `${BULLET}Validation Error`, + message, + DOCUMENTATION_NOTE + ); +const resolve = (resolver, {key, filePath, rootDir, optional}) => { + const module = _jestResolve().default.findNodeModule( + replaceRootDirInPath(rootDir, filePath), + { + basedir: rootDir, + resolver: resolver || undefined + } + ); + if (!module && !optional) { + throw createValidationError(` Module ${_chalk().default.bold( + filePath + )} in the ${_chalk().default.bold(key)} option was not found. + ${_chalk().default.bold('')} is: ${rootDir}`); + } + /// can cast as string since nulls will be thrown + return module; +}; +exports.resolve = resolve; +const escapeGlobCharacters = path => path.replace(/([()*{}[\]!?\\])/g, '\\$1'); +exports.escapeGlobCharacters = escapeGlobCharacters; +const replaceRootDirInPath = (rootDir, filePath) => { + if (!/^/.test(filePath)) { + return filePath; + } + return path().resolve( + rootDir, + path().normalize(`./${filePath.substring(''.length)}`) + ); +}; +exports.replaceRootDirInPath = replaceRootDirInPath; +const _replaceRootDirInObject = (rootDir, config) => { + const newConfig = {}; + for (const configKey in config) { + newConfig[configKey] = + configKey === 'rootDir' + ? config[configKey] + : _replaceRootDirTags(rootDir, config[configKey]); + } + return newConfig; +}; +const _replaceRootDirTags = (rootDir, config) => { + if (config == null) { + return config; + } + switch (typeof config) { + case 'object': + if (Array.isArray(config)) { + /// can be string[] or {}[] + return config.map(item => _replaceRootDirTags(rootDir, item)); + } + if (config instanceof RegExp) { + return config; + } + return _replaceRootDirInObject(rootDir, config); + case 'string': + return replaceRootDirInPath(rootDir, config); + } + return config; +}; +exports._replaceRootDirTags = _replaceRootDirTags; +// newtype +const isJSONString = text => + text != null && + typeof text === 'string' && + text.startsWith('{') && + text.endsWith('}'); +exports.isJSONString = isJSONString; diff --git a/node_modules/jest-config/build/validatePattern.js b/node_modules/jest-config/build/validatePattern.js new file mode 100644 index 0000000..c3b0e7d --- /dev/null +++ b/node_modules/jest-config/build/validatePattern.js @@ -0,0 +1,24 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = validatePattern; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function validatePattern(pattern) { + if (pattern) { + try { + // eslint-disable-next-line no-new + new RegExp(pattern, 'i'); + } catch { + return false; + } + } + return true; +} diff --git a/node_modules/jest-config/package.json b/node_modules/jest-config/package.json new file mode 100644 index 0000000..2a4edf7 --- /dev/null +++ b/node_modules/jest-config/package.json @@ -0,0 +1,70 @@ +{ + "name": "jest-config", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-config" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "peerDependencies": { + "@types/node": "*", + "ts-node": ">=9.0.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "ts-node": { + "optional": true + } + }, + "dependencies": { + "@babel/core": "^7.11.6", + "@jest/test-sequencer": "^29.2.2", + "@jest/types": "^29.2.1", + "babel-jest": "^29.2.2", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "deepmerge": "^4.2.2", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-circus": "^29.2.2", + "jest-environment-node": "^29.2.2", + "jest-get-type": "^29.2.0", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.2.2", + "jest-runner": "^29.2.2", + "jest-util": "^29.2.1", + "jest-validate": "^29.2.2", + "micromatch": "^4.0.4", + "parse-json": "^5.2.0", + "pretty-format": "^29.2.1", + "slash": "^3.0.0", + "strip-json-comments": "^3.1.1" + }, + "devDependencies": { + "@types/glob": "^7.1.1", + "@types/graceful-fs": "^4.1.3", + "@types/micromatch": "^4.0.1", + "semver": "^7.3.5", + "ts-node": "^10.5.0", + "typescript": "^4.8.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-diff/LICENSE b/node_modules/jest-diff/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-diff/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-diff/README.md b/node_modules/jest-diff/README.md new file mode 100644 index 0000000..d52f821 --- /dev/null +++ b/node_modules/jest-diff/README.md @@ -0,0 +1,671 @@ +# jest-diff + +Display differences clearly so people can review changes confidently. + +The `diff` named export serializes JavaScript **values**, compares them line-by-line, and returns a string which includes comparison lines. + +Two named exports compare **strings** character-by-character: + +- `diffStringsUnified` returns a string. +- `diffStringsRaw` returns an array of `Diff` objects. + +Three named exports compare **arrays of strings** line-by-line: + +- `diffLinesUnified` and `diffLinesUnified2` return a string. +- `diffLinesRaw` returns an array of `Diff` objects. + +## Installation + +To add this package as a dependency of a project, run either of the following commands: + +- `npm install jest-diff` +- `yarn add jest-diff` + +## Usage of `diff()` + +Given JavaScript **values**, `diff(a, b, options?)` does the following: + +1. **serialize** the values as strings using the `pretty-format` package +2. **compare** the strings line-by-line using the `diff-sequences` package +3. **format** the changed or common lines using the `chalk` package + +To use this function, write either of the following: + +- `const {diff} = require('jest-diff');` in CommonJS modules +- `import {diff} from 'jest-diff';` in ECMAScript modules + +### Example of `diff()` + +```js +const a = ['delete', 'common', 'changed from']; +const b = ['common', 'changed to', 'insert']; + +const difference = diff(a, b); +``` + +The returned **string** consists of: + +- annotation lines: describe the two change indicators with labels, and a blank line +- comparison lines: similar to “unified” view on GitHub, but `Expected` lines are green, `Received` lines are red, and common lines are dim (by default, see Options) + +```diff +- Expected ++ Received + + Array [ +- "delete", + "common", +- "changed from", ++ "changed to", ++ "insert", + ] +``` + +### Edge cases of `diff()` + +Here are edge cases for the return value: + +- `' Comparing two different types of values. …'` if the arguments have **different types** according to the `jest-get-type` package (instances of different classes have the same `'object'` type) +- `'Compared values have no visual difference.'` if the arguments have either **referential identity** according to `Object.is` method or **same serialization** according to the `pretty-format` package +- `null` if either argument is a so-called **asymmetric matcher** in Jasmine or Jest + +## Usage of diffStringsUnified + +Given **strings**, `diffStringsUnified(a, b, options?)` does the following: + +1. **compare** the strings character-by-character using the `diff-sequences` package +2. **clean up** small (often coincidental) common substrings, also known as chaff +3. **format** the changed or common lines using the `chalk` package + +Although the function is mainly for **multiline** strings, it compares any strings. + +Write either of the following: + +- `const {diffStringsUnified} = require('jest-diff');` in CommonJS modules +- `import {diffStringsUnified} from 'jest-diff';` in ECMAScript modules + +### Example of diffStringsUnified + +```js +const a = 'common\nchanged from'; +const b = 'common\nchanged to'; + +const difference = diffStringsUnified(a, b); +``` + +The returned **string** consists of: + +- annotation lines: describe the two change indicators with labels, and a blank line +- comparison lines: similar to “unified” view on GitHub, and **changed substrings** have **inverse** foreground and background colors (that is, `from` has white-on-green and `to` has white-on-red, which the following example does not show) + +```diff +- Expected ++ Received + + common +- changed from ++ changed to +``` + +### Performance of diffStringsUnified + +To get the benefit of **changed substrings** within the comparison lines, a character-by-character comparison has a higher computational cost (in time and space) than a line-by-line comparison. + +If the input strings can have **arbitrary length**, we recommend that the calling code set a limit, beyond which splits the strings, and then calls `diffLinesUnified` instead. For example, Jest falls back to line-by-line comparison if either string has length greater than 20K characters. + +## Usage of diffLinesUnified + +Given **arrays of strings**, `diffLinesUnified(aLines, bLines, options?)` does the following: + +1. **compare** the arrays line-by-line using the `diff-sequences` package +2. **format** the changed or common lines using the `chalk` package + +You might call this function when strings have been split into lines and you do not need to see changed substrings within lines. + +### Example of diffLinesUnified + +```js +const aLines = ['delete', 'common', 'changed from']; +const bLines = ['common', 'changed to', 'insert']; + +const difference = diffLinesUnified(aLines, bLines); +``` + +```diff +- Expected ++ Received + +- delete + common +- changed from ++ changed to ++ insert +``` + +### Edge cases of diffLinesUnified or diffStringsUnified + +Here are edge cases for arguments and return values: + +- both `a` and `b` are empty strings: no comparison lines +- only `a` is empty string: all comparison lines have `bColor` and `bIndicator` (see Options) +- only `b` is empty string: all comparison lines have `aColor` and `aIndicator` (see Options) +- `a` and `b` are equal non-empty strings: all comparison lines have `commonColor` and `commonIndicator` (see Options) + +## Usage of diffLinesUnified2 + +Given two **pairs** of arrays of strings, `diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options?)` does the following: + +1. **compare** the pair of `Compare` arrays line-by-line using the `diff-sequences` package +2. **format** the corresponding lines in the pair of `Display` arrays using the `chalk` package + +Jest calls this function to consider lines as common instead of changed if the only difference is indentation. + +You might call this function for case insensitive or Unicode equivalence comparison of lines. + +### Example of diffLinesUnified2 + +```js +import {format} from 'pretty-format'; + +const a = { + text: 'Ignore indentation in serialized object', + time: '2019-09-19T12:34:56.000Z', + type: 'CREATE_ITEM', +}; +const b = { + payload: { + text: 'Ignore indentation in serialized object', + time: '2019-09-19T12:34:56.000Z', + }, + type: 'CREATE_ITEM', +}; + +const difference = diffLinesUnified2( + // serialize with indentation to display lines + format(a).split('\n'), + format(b).split('\n'), + // serialize without indentation to compare lines + format(a, {indent: 0}).split('\n'), + format(b, {indent: 0}).split('\n'), +); +``` + +The `text` and `time` properties are common, because their only difference is indentation: + +```diff +- Expected ++ Received + + Object { ++ payload: Object { + text: 'Ignore indentation in serialized object', + time: '2019-09-19T12:34:56.000Z', ++ }, + type: 'CREATE_ITEM', + } +``` + +The preceding example illustrates why (at least for indentation) it seems more intuitive that the function returns the common line from the `bLinesDisplay` array instead of from the `aLinesDisplay` array. + +## Usage of diffStringsRaw + +Given **strings** and a boolean option, `diffStringsRaw(a, b, cleanup)` does the following: + +1. **compare** the strings character-by-character using the `diff-sequences` package +2. optionally **clean up** small (often coincidental) common substrings, also known as chaff + +Because `diffStringsRaw` returns the difference as **data** instead of a string, you can format it as your application requires (for example, enclosed in HTML markup for browser instead of escape sequences for console). + +The returned **array** describes substrings as instances of the `Diff` class, which calling code can access like array tuples: + +The value at index `0` is one of the following: + +| value | named export | description | +| ----: | :------------ | :-------------------- | +| `0` | `DIFF_EQUAL` | in `a` and in `b` | +| `-1` | `DIFF_DELETE` | in `a` but not in `b` | +| `1` | `DIFF_INSERT` | in `b` but not in `a` | + +The value at index `1` is a substring of `a` or `b` or both. + +### Example of diffStringsRaw with cleanup + +```js +const diffs = diffStringsRaw('changed from', 'changed to', true); +``` + +| `i` | `diffs[i][0]` | `diffs[i][1]` | +| --: | ------------: | :------------ | +| `0` | `0` | `'changed '` | +| `1` | `-1` | `'from'` | +| `2` | `1` | `'to'` | + +### Example of diffStringsRaw without cleanup + +```js +const diffs = diffStringsRaw('changed from', 'changed to', false); +``` + +| `i` | `diffs[i][0]` | `diffs[i][1]` | +| --: | ------------: | :------------ | +| `0` | `0` | `'changed '` | +| `1` | `-1` | `'fr'` | +| `2` | `1` | `'t'` | +| `3` | `0` | `'o'` | +| `4` | `-1` | `'m'` | + +### Advanced import for diffStringsRaw + +Here are all the named imports that you might need for the `diffStringsRaw` function: + +- `const {DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diffStringsRaw} = require('jest-diff');` in CommonJS modules +- `import {DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, Diff, diffStringsRaw} from 'jest-diff';` in ECMAScript modules + +To write a **formatting** function, you might need the named constants (and `Diff` in TypeScript annotations). + +If you write an application-specific **cleanup** algorithm, then you might need to call the `Diff` constructor: + +```js +const diffCommon = new Diff(DIFF_EQUAL, 'changed '); +const diffDelete = new Diff(DIFF_DELETE, 'from'); +const diffInsert = new Diff(DIFF_INSERT, 'to'); +``` + +## Usage of diffLinesRaw + +Given **arrays of strings**, `diffLinesRaw(aLines, bLines)` does the following: + +- **compare** the arrays line-by-line using the `diff-sequences` package + +Because `diffLinesRaw` returns the difference as **data** instead of a string, you can format it as your application requires. + +### Example of diffLinesRaw + +```js +const aLines = ['delete', 'common', 'changed from']; +const bLines = ['common', 'changed to', 'insert']; + +const diffs = diffLinesRaw(aLines, bLines); +``` + +| `i` | `diffs[i][0]` | `diffs[i][1]` | +| --: | ------------: | :--------------- | +| `0` | `-1` | `'delete'` | +| `1` | `0` | `'common'` | +| `2` | `-1` | `'changed from'` | +| `3` | `1` | `'changed to'` | +| `4` | `1` | `'insert'` | + +### Edge case of diffLinesRaw + +If you call `string.split('\n')` for an empty string: + +- the result is `['']` an array which contains an empty string +- instead of `[]` an empty array + +Depending of your application, you might call `diffLinesRaw` with either array. + +### Example of split method + +```js +import {diffLinesRaw} from 'jest-diff'; + +const a = 'non-empty string'; +const b = ''; + +const diffs = diffLinesRaw(a.split('\n'), b.split('\n')); +``` + +| `i` | `diffs[i][0]` | `diffs[i][1]` | +| --: | ------------: | :------------------- | +| `0` | `-1` | `'non-empty string'` | +| `1` | `1` | `''` | + +Which you might format as follows: + +```diff +- Expected - 1 ++ Received + 1 + +- non-empty string ++ +``` + +### Example of splitLines0 function + +For edge case behavior like the `diffLinesUnified` function, you might define a `splitLines0` function, which given an empty string, returns `[]` an empty array: + +```js +export const splitLines0 = string => + string.length === 0 ? [] : string.split('\n'); +``` + +```js +import {diffLinesRaw} from 'jest-diff'; + +const a = ''; +const b = 'line 1\nline 2\nline 3'; + +const diffs = diffLinesRaw(a.split('\n'), b.split('\n')); +``` + +| `i` | `diffs[i][0]` | `diffs[i][1]` | +| --: | ------------: | :------------ | +| `0` | `1` | `'line 1'` | +| `1` | `1` | `'line 2'` | +| `2` | `1` | `'line 3'` | + +Which you might format as follows: + +```diff +- Expected - 0 ++ Received + 3 + ++ line 1 ++ line 2 ++ line 3 +``` + +In contrast to the `diffLinesRaw` function, the `diffLinesUnified` and `diffLinesUnified2` functions **automatically** convert array arguments computed by string `split` method, so callers do **not** need a `splitLine0` function. + +## Options + +The default options are for the report when an assertion fails from the `expect` package used by Jest. + +For other applications, you can provide an options object as a third argument: + +- `diff(a, b, options)` +- `diffStringsUnified(a, b, options)` +- `diffLinesUnified(aLines, bLines, options)` +- `diffLinesUnified2(aLinesDisplay, bLinesDisplay, aLinesCompare, bLinesCompare, options)` + +### Properties of options object + +| name | default | +| :-------------------------------- | :----------------- | +| `aAnnotation` | `'Expected'` | +| `aColor` | `chalk.green` | +| `aIndicator` | `'-'` | +| `bAnnotation` | `'Received'` | +| `bColor` | `chalk.red` | +| `bIndicator` | `'+'` | +| `changeColor` | `chalk.inverse` | +| `changeLineTrailingSpaceColor` | `string => string` | +| `commonColor` | `chalk.dim` | +| `commonIndicator` | `' '` | +| `commonLineTrailingSpaceColor` | `string => string` | +| `compareKeys` | `undefined` | +| `contextLines` | `5` | +| `emptyFirstOrLastLinePlaceholder` | `''` | +| `expand` | `true` | +| `includeChangeCounts` | `false` | +| `omitAnnotationLines` | `false` | +| `patchColor` | `chalk.yellow` | + +For more information about the options, see the following examples. + +### Example of options for labels + +If the application is code modification, you might replace the labels: + +```js +const options = { + aAnnotation: 'Original', + bAnnotation: 'Modified', +}; +``` + +```diff +- Original ++ Modified + + common +- changed from ++ changed to +``` + +The `jest-diff` package does not assume that the 2 labels have equal length. + +### Example of options for colors of changed lines + +For consistency with most diff tools, you might exchange the colors: + +```ts +import chalk = require('chalk'); + +const options = { + aColor: chalk.red, + bColor: chalk.green, +}; +``` + +### Example of option for color of changed substrings + +Although the default inverse of foreground and background colors is hard to beat for changed substrings **within lines**, especially because it highlights spaces, if you want bold font weight on yellow background color: + +```ts +import chalk = require('chalk'); + +const options = { + changeColor: chalk.bold.bgYellowBright, +}; +``` + +### Example of option to format trailing spaces + +Because `diff()` does not display substring differences within lines, formatting can help you see when lines differ by the presence or absence of trailing spaces found by `/\s+$/` regular expression. + +- If change lines have a background color, then you can see trailing spaces. +- If common lines have default dim color, then you cannot see trailing spaces. You might want yellowish background color to see them. + +```js +const options = { + aColor: chalk.rgb(128, 0, 128).bgRgb(255, 215, 255), // magenta + bColor: chalk.rgb(0, 95, 0).bgRgb(215, 255, 215), // green + commonLineTrailingSpaceColor: chalk.bgYellow, +}; +``` + +The value of a Color option is a function, which given a string, returns a string. + +If you want to replace trailing spaces with middle dot characters: + +```js +const replaceSpacesWithMiddleDot = string => '·'.repeat(string.length); + +const options = { + changeLineTrailingSpaceColor: replaceSpacesWithMiddleDot, + commonLineTrailingSpaceColor: replaceSpacesWithMiddleDot, +}; +``` + +If you need the TypeScript type of a Color option: + +```ts +import {DiffOptionsColor} from 'jest-diff'; +``` + +### Example of options for no colors + +To store the difference in a file without escape codes for colors, provide an identity function: + +```js +const noColor = string => string; + +const options = { + aColor: noColor, + bColor: noColor, + changeColor: noColor, + commonColor: noColor, + patchColor: noColor, +}; +``` + +### Example of options for indicators + +For consistency with the `diff` command, you might replace the indicators: + +```js +const options = { + aIndicator: '<', + bIndicator: '>', +}; +``` + +The `jest-diff` package assumes (but does not enforce) that the 3 indicators have equal length. + +### Example of options to limit common lines + +By default, the output includes all common lines. + +To emphasize the changes, you might limit the number of common “context” lines: + +```js +const options = { + contextLines: 1, + expand: false, +}; +``` + +A patch mark like `@@ -12,7 +12,9 @@` accounts for omitted common lines. + +### Example of option for color of patch marks + +If you want patch marks to have the same dim color as common lines: + +```ts +import chalk = require('chalk'); + +const options = { + expand: false, + patchColor: chalk.dim, +}; +``` + +### Example of option to include change counts + +To display the number of changed lines at the right of annotation lines: + +```js +const a = ['common', 'changed from']; +const b = ['common', 'changed to', 'insert']; + +const options = { + includeChangeCounts: true, +}; + +const difference = diff(a, b, options); +``` + +```diff +- Expected - 1 ++ Received + 2 + + Array [ + "common", +- "changed from", ++ "changed to", ++ "insert", + ] +``` + +### Example of option to omit annotation lines + +To display only the comparison lines: + +```js +const a = 'common\nchanged from'; +const b = 'common\nchanged to'; + +const options = { + omitAnnotationLines: true, +}; + +const difference = diffStringsUnified(a, b, options); +``` + +```diff + common +- changed from ++ changed to +``` + +### Example of option for empty first or last lines + +If the **first** or **last** comparison line is **empty**, because the content is empty and the indicator is a space, you might not notice it. + +The replacement option is a string whose default value is `''` empty string. + +Because Jest trims the report when a matcher fails, it deletes an empty last line. + +Therefore, Jest uses as placeholder the downwards arrow with corner leftwards: + +```js +const options = { + emptyFirstOrLastLinePlaceholder: '↵', // U+21B5 +}; +``` + +If a content line is empty, then the corresponding comparison line is automatically trimmed to remove the margin space (represented as a middle dot below) for the default indicators: + +| Indicator | untrimmed | trimmed | +| ----------------: | :-------- | :------ | +| `aIndicator` | `'-·'` | `'-'` | +| `bIndicator` | `'+·'` | `'+'` | +| `commonIndicator` | `' ·'` | `''` | + +### Example of option for sorting object keys + +When two objects are compared their keys are printed in alphabetical order by default. If this was not the original order of the keys the diff becomes harder to read as the keys are not in their original position. + +Use `compareKeys` to pass a function which will be used when sorting the object keys. + +```js +const a = {c: 'c', b: 'b1', a: 'a'}; +const b = {c: 'c', b: 'b2', a: 'a'}; + +const options = { + // The keys will be in their original order + compareKeys: () => 0, +}; + +const difference = diff(a, b, options); +``` + +```diff +- Expected ++ Received + + Object { + "c": "c", +- "b": "b1", ++ "b": "b2", + "a": "a", + } +``` + +Depending on the implementation of `compareKeys` any sort order can be used. + +```js +const a = {c: 'c', b: 'b1', a: 'a'}; +const b = {c: 'c', b: 'b2', a: 'a'}; + +const options = { + // The keys will be in reverse order + compareKeys: (a, b) => (a > b ? -1 : 1), +}; + +const difference = diff(a, b, options); +``` + +```diff +- Expected ++ Received + + Object { + "a": "a", +- "b": "b1", ++ "b": "b2", + "c": "c", + } +``` diff --git a/node_modules/jest-diff/build/cleanupSemantic.js b/node_modules/jest-diff/build/cleanupSemantic.js new file mode 100644 index 0000000..bc84226 --- /dev/null +++ b/node_modules/jest-diff/build/cleanupSemantic.js @@ -0,0 +1,599 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.cleanupSemantic = + exports.Diff = + exports.DIFF_INSERT = + exports.DIFF_EQUAL = + exports.DIFF_DELETE = + void 0; +/** + * Diff Match and Patch + * Copyright 2018 The diff-match-patch Authors. + * https://github.com/google/diff-match-patch + * + * 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. + */ + +/** + * @fileoverview Computes the difference between two texts to create a patch. + * Applies the patch onto another text, allowing for errors. + * @author fraser@google.com (Neil Fraser) + */ + +/** + * CHANGES by pedrottimark to diff_match_patch_uncompressed.ts file: + * + * 1. Delete anything not needed to use diff_cleanupSemantic method + * 2. Convert from prototype properties to var declarations + * 3. Convert Diff to class from constructor and prototype + * 4. Add type annotations for arguments and return values + * 5. Add exports + */ + +/** + * The data structure representing a diff is an array of tuples: + * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] + * which means: delete 'Hello', add 'Goodbye' and keep ' world.' + */ +var DIFF_DELETE = -1; +exports.DIFF_DELETE = DIFF_DELETE; +var DIFF_INSERT = 1; +exports.DIFF_INSERT = DIFF_INSERT; +var DIFF_EQUAL = 0; + +/** + * Class representing one diff tuple. + * Attempts to look like a two-element array (which is what this used to be). + * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. + * @param {string} text Text to be deleted, inserted, or retained. + * @constructor + */ +exports.DIFF_EQUAL = DIFF_EQUAL; +class Diff { + 0; + 1; + constructor(op, text) { + this[0] = op; + this[1] = text; + } +} + +/** + * Determine the common prefix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the start of each + * string. + */ +exports.Diff = Diff; +var diff_commonPrefix = function (text1, text2) { + // Quick check for common null cases. + if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { + return 0; + } + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + var pointermin = 0; + var pointermax = Math.min(text1.length, text2.length); + var pointermid = pointermax; + var pointerstart = 0; + while (pointermin < pointermid) { + if ( + text1.substring(pointerstart, pointermid) == + text2.substring(pointerstart, pointermid) + ) { + pointermin = pointermid; + pointerstart = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; +}; + +/** + * Determine the common suffix of two strings. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of each string. + */ +var diff_commonSuffix = function (text1, text2) { + // Quick check for common null cases. + if ( + !text1 || + !text2 || + text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1) + ) { + return 0; + } + // Binary search. + // Performance analysis: https://neil.fraser.name/news/2007/10/09/ + var pointermin = 0; + var pointermax = Math.min(text1.length, text2.length); + var pointermid = pointermax; + var pointerend = 0; + while (pointermin < pointermid) { + if ( + text1.substring(text1.length - pointermid, text1.length - pointerend) == + text2.substring(text2.length - pointermid, text2.length - pointerend) + ) { + pointermin = pointermid; + pointerend = pointermin; + } else { + pointermax = pointermid; + } + pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); + } + return pointermid; +}; + +/** + * Determine if the suffix of one string is the prefix of another. + * @param {string} text1 First string. + * @param {string} text2 Second string. + * @return {number} The number of characters common to the end of the first + * string and the start of the second string. + * @private + */ +var diff_commonOverlap_ = function (text1, text2) { + // Cache the text lengths to prevent multiple calls. + var text1_length = text1.length; + var text2_length = text2.length; + // Eliminate the null case. + if (text1_length == 0 || text2_length == 0) { + return 0; + } + // Truncate the longer string. + if (text1_length > text2_length) { + text1 = text1.substring(text1_length - text2_length); + } else if (text1_length < text2_length) { + text2 = text2.substring(0, text1_length); + } + var text_length = Math.min(text1_length, text2_length); + // Quick check for the worst case. + if (text1 == text2) { + return text_length; + } + + // Start by looking for a single character match + // and increase length until no match is found. + // Performance analysis: https://neil.fraser.name/news/2010/11/04/ + var best = 0; + var length = 1; + while (true) { + var pattern = text1.substring(text_length - length); + var found = text2.indexOf(pattern); + if (found == -1) { + return best; + } + length += found; + if ( + found == 0 || + text1.substring(text_length - length) == text2.substring(0, length) + ) { + best = length; + length++; + } + } +}; + +/** + * Reduce the number of edits by eliminating semantically trivial equalities. + * @param {!Array.} diffs Array of diff tuples. + */ +var diff_cleanupSemantic = function (diffs) { + var changes = false; + var equalities = []; // Stack of indices where equalities are found. + var equalitiesLength = 0; // Keeping our own length var is faster in JS. + /** @type {?string} */ + var lastEquality = null; + // Always equal to diffs[equalities[equalitiesLength - 1]][1] + var pointer = 0; // Index of current position. + // Number of characters that changed prior to the equality. + var length_insertions1 = 0; + var length_deletions1 = 0; + // Number of characters that changed after the equality. + var length_insertions2 = 0; + var length_deletions2 = 0; + while (pointer < diffs.length) { + if (diffs[pointer][0] == DIFF_EQUAL) { + // Equality found. + equalities[equalitiesLength++] = pointer; + length_insertions1 = length_insertions2; + length_deletions1 = length_deletions2; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = diffs[pointer][1]; + } else { + // An insertion or deletion. + if (diffs[pointer][0] == DIFF_INSERT) { + length_insertions2 += diffs[pointer][1].length; + } else { + length_deletions2 += diffs[pointer][1].length; + } + // Eliminate an equality that is smaller or equal to the edits on both + // sides of it. + if ( + lastEquality && + lastEquality.length <= + Math.max(length_insertions1, length_deletions1) && + lastEquality.length <= Math.max(length_insertions2, length_deletions2) + ) { + // Duplicate record. + diffs.splice( + equalities[equalitiesLength - 1], + 0, + new Diff(DIFF_DELETE, lastEquality) + ); + // Change second copy to insert. + diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; + // Throw away the equality we just deleted. + equalitiesLength--; + // Throw away the previous equality (it needs to be reevaluated). + equalitiesLength--; + pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; + length_insertions1 = 0; // Reset the counters. + length_deletions1 = 0; + length_insertions2 = 0; + length_deletions2 = 0; + lastEquality = null; + changes = true; + } + } + pointer++; + } + + // Normalize the diff. + if (changes) { + diff_cleanupMerge(diffs); + } + diff_cleanupSemanticLossless(diffs); + + // Find any overlaps between deletions and insertions. + // e.g: abcxxxxxxdef + // -> abcxxxdef + // e.g: xxxabcdefxxx + // -> defxxxabc + // Only extract an overlap if it is as big as the edit ahead or behind it. + pointer = 1; + while (pointer < diffs.length) { + if ( + diffs[pointer - 1][0] == DIFF_DELETE && + diffs[pointer][0] == DIFF_INSERT + ) { + var deletion = diffs[pointer - 1][1]; + var insertion = diffs[pointer][1]; + var overlap_length1 = diff_commonOverlap_(deletion, insertion); + var overlap_length2 = diff_commonOverlap_(insertion, deletion); + if (overlap_length1 >= overlap_length2) { + if ( + overlap_length1 >= deletion.length / 2 || + overlap_length1 >= insertion.length / 2 + ) { + // Overlap found. Insert an equality and trim the surrounding edits. + diffs.splice( + pointer, + 0, + new Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1)) + ); + diffs[pointer - 1][1] = deletion.substring( + 0, + deletion.length - overlap_length1 + ); + diffs[pointer + 1][1] = insertion.substring(overlap_length1); + pointer++; + } + } else { + if ( + overlap_length2 >= deletion.length / 2 || + overlap_length2 >= insertion.length / 2 + ) { + // Reverse overlap found. + // Insert an equality and swap and trim the surrounding edits. + diffs.splice( + pointer, + 0, + new Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2)) + ); + diffs[pointer - 1][0] = DIFF_INSERT; + diffs[pointer - 1][1] = insertion.substring( + 0, + insertion.length - overlap_length2 + ); + diffs[pointer + 1][0] = DIFF_DELETE; + diffs[pointer + 1][1] = deletion.substring(overlap_length2); + pointer++; + } + } + pointer++; + } + pointer++; + } +}; + +/** + * Look for single edits surrounded on both sides by equalities + * which can be shifted sideways to align the edit to a word boundary. + * e.g: The cat came. -> The cat came. + * @param {!Array.} diffs Array of diff tuples. + */ +exports.cleanupSemantic = diff_cleanupSemantic; +var diff_cleanupSemanticLossless = function (diffs) { + /** + * Given two strings, compute a score representing whether the internal + * boundary falls on logical boundaries. + * Scores range from 6 (best) to 0 (worst). + * Closure, but does not reference any external variables. + * @param {string} one First string. + * @param {string} two Second string. + * @return {number} The score. + * @private + */ + function diff_cleanupSemanticScore_(one, two) { + if (!one || !two) { + // Edges are the best. + return 6; + } + + // Each port of this function behaves slightly differently due to + // subtle differences in each language's definition of things like + // 'whitespace'. Since this function's purpose is largely cosmetic, + // the choice has been made to use each language's native features + // rather than force total conformity. + var char1 = one.charAt(one.length - 1); + var char2 = two.charAt(0); + var nonAlphaNumeric1 = char1.match(nonAlphaNumericRegex_); + var nonAlphaNumeric2 = char2.match(nonAlphaNumericRegex_); + var whitespace1 = nonAlphaNumeric1 && char1.match(whitespaceRegex_); + var whitespace2 = nonAlphaNumeric2 && char2.match(whitespaceRegex_); + var lineBreak1 = whitespace1 && char1.match(linebreakRegex_); + var lineBreak2 = whitespace2 && char2.match(linebreakRegex_); + var blankLine1 = lineBreak1 && one.match(blanklineEndRegex_); + var blankLine2 = lineBreak2 && two.match(blanklineStartRegex_); + if (blankLine1 || blankLine2) { + // Five points for blank lines. + return 5; + } else if (lineBreak1 || lineBreak2) { + // Four points for line breaks. + return 4; + } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { + // Three points for end of sentences. + return 3; + } else if (whitespace1 || whitespace2) { + // Two points for whitespace. + return 2; + } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { + // One point for non-alphanumeric. + return 1; + } + return 0; + } + var pointer = 1; + // Intentionally ignore the first and last element (don't need checking). + while (pointer < diffs.length - 1) { + if ( + diffs[pointer - 1][0] == DIFF_EQUAL && + diffs[pointer + 1][0] == DIFF_EQUAL + ) { + // This is a single edit surrounded by equalities. + var equality1 = diffs[pointer - 1][1]; + var edit = diffs[pointer][1]; + var equality2 = diffs[pointer + 1][1]; + + // First, shift the edit as far left as possible. + var commonOffset = diff_commonSuffix(equality1, edit); + if (commonOffset) { + var commonString = edit.substring(edit.length - commonOffset); + equality1 = equality1.substring(0, equality1.length - commonOffset); + edit = commonString + edit.substring(0, edit.length - commonOffset); + equality2 = commonString + equality2; + } + + // Second, step character by character right, looking for the best fit. + var bestEquality1 = equality1; + var bestEdit = edit; + var bestEquality2 = equality2; + var bestScore = + diff_cleanupSemanticScore_(equality1, edit) + + diff_cleanupSemanticScore_(edit, equality2); + while (edit.charAt(0) === equality2.charAt(0)) { + equality1 += edit.charAt(0); + edit = edit.substring(1) + equality2.charAt(0); + equality2 = equality2.substring(1); + var score = + diff_cleanupSemanticScore_(equality1, edit) + + diff_cleanupSemanticScore_(edit, equality2); + // The >= encourages trailing rather than leading whitespace on edits. + if (score >= bestScore) { + bestScore = score; + bestEquality1 = equality1; + bestEdit = edit; + bestEquality2 = equality2; + } + } + if (diffs[pointer - 1][1] != bestEquality1) { + // We have an improvement, save it back to the diff. + if (bestEquality1) { + diffs[pointer - 1][1] = bestEquality1; + } else { + diffs.splice(pointer - 1, 1); + pointer--; + } + diffs[pointer][1] = bestEdit; + if (bestEquality2) { + diffs[pointer + 1][1] = bestEquality2; + } else { + diffs.splice(pointer + 1, 1); + pointer--; + } + } + } + pointer++; + } +}; + +// Define some regex patterns for matching boundaries. +var nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; +var whitespaceRegex_ = /\s/; +var linebreakRegex_ = /[\r\n]/; +var blanklineEndRegex_ = /\n\r?\n$/; +var blanklineStartRegex_ = /^\r?\n\r?\n/; + +/** + * Reorder and merge like edit sections. Merge equalities. + * Any edit section can move as long as it doesn't cross an equality. + * @param {!Array.} diffs Array of diff tuples. + */ +var diff_cleanupMerge = function (diffs) { + // Add a dummy entry at the end. + diffs.push(new Diff(DIFF_EQUAL, '')); + var pointer = 0; + var count_delete = 0; + var count_insert = 0; + var text_delete = ''; + var text_insert = ''; + var commonlength; + while (pointer < diffs.length) { + switch (diffs[pointer][0]) { + case DIFF_INSERT: + count_insert++; + text_insert += diffs[pointer][1]; + pointer++; + break; + case DIFF_DELETE: + count_delete++; + text_delete += diffs[pointer][1]; + pointer++; + break; + case DIFF_EQUAL: + // Upon reaching an equality, check for prior redundancies. + if (count_delete + count_insert > 1) { + if (count_delete !== 0 && count_insert !== 0) { + // Factor out any common prefixies. + commonlength = diff_commonPrefix(text_insert, text_delete); + if (commonlength !== 0) { + if ( + pointer - count_delete - count_insert > 0 && + diffs[pointer - count_delete - count_insert - 1][0] == + DIFF_EQUAL + ) { + diffs[pointer - count_delete - count_insert - 1][1] += + text_insert.substring(0, commonlength); + } else { + diffs.splice( + 0, + 0, + new Diff(DIFF_EQUAL, text_insert.substring(0, commonlength)) + ); + pointer++; + } + text_insert = text_insert.substring(commonlength); + text_delete = text_delete.substring(commonlength); + } + // Factor out any common suffixies. + commonlength = diff_commonSuffix(text_insert, text_delete); + if (commonlength !== 0) { + diffs[pointer][1] = + text_insert.substring(text_insert.length - commonlength) + + diffs[pointer][1]; + text_insert = text_insert.substring( + 0, + text_insert.length - commonlength + ); + text_delete = text_delete.substring( + 0, + text_delete.length - commonlength + ); + } + } + // Delete the offending records and add the merged ones. + pointer -= count_delete + count_insert; + diffs.splice(pointer, count_delete + count_insert); + if (text_delete.length) { + diffs.splice(pointer, 0, new Diff(DIFF_DELETE, text_delete)); + pointer++; + } + if (text_insert.length) { + diffs.splice(pointer, 0, new Diff(DIFF_INSERT, text_insert)); + pointer++; + } + pointer++; + } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) { + // Merge this equality with the previous one. + diffs[pointer - 1][1] += diffs[pointer][1]; + diffs.splice(pointer, 1); + } else { + pointer++; + } + count_insert = 0; + count_delete = 0; + text_delete = ''; + text_insert = ''; + break; + } + } + if (diffs[diffs.length - 1][1] === '') { + diffs.pop(); // Remove the dummy entry at the end. + } + + // Second pass: look for single edits surrounded on both sides by equalities + // which can be shifted sideways to eliminate an equality. + // e.g: ABAC -> ABAC + var changes = false; + pointer = 1; + // Intentionally ignore the first and last element (don't need checking). + while (pointer < diffs.length - 1) { + if ( + diffs[pointer - 1][0] == DIFF_EQUAL && + diffs[pointer + 1][0] == DIFF_EQUAL + ) { + // This is a single edit surrounded by equalities. + if ( + diffs[pointer][1].substring( + diffs[pointer][1].length - diffs[pointer - 1][1].length + ) == diffs[pointer - 1][1] + ) { + // Shift the edit over the previous equality. + diffs[pointer][1] = + diffs[pointer - 1][1] + + diffs[pointer][1].substring( + 0, + diffs[pointer][1].length - diffs[pointer - 1][1].length + ); + diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; + diffs.splice(pointer - 1, 1); + changes = true; + } else if ( + diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == + diffs[pointer + 1][1] + ) { + // Shift the edit over the next equality. + diffs[pointer - 1][1] += diffs[pointer + 1][1]; + diffs[pointer][1] = + diffs[pointer][1].substring(diffs[pointer + 1][1].length) + + diffs[pointer + 1][1]; + diffs.splice(pointer + 1, 1); + changes = true; + } + } + pointer++; + } + // If shifts were made, the diff needs reordering and another shift sweep. + if (changes) { + diff_cleanupMerge(diffs); + } +}; diff --git a/node_modules/jest-diff/build/constants.js b/node_modules/jest-diff/build/constants.js new file mode 100644 index 0000000..e6741c8 --- /dev/null +++ b/node_modules/jest-diff/build/constants.js @@ -0,0 +1,19 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.SIMILAR_MESSAGE = exports.NO_DIFF_MESSAGE = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const NO_DIFF_MESSAGE = 'Compared values have no visual difference.'; +exports.NO_DIFF_MESSAGE = NO_DIFF_MESSAGE; +const SIMILAR_MESSAGE = + 'Compared values serialize to the same structure.\n' + + 'Printing internal object structure without calling `toJSON` instead.'; +exports.SIMILAR_MESSAGE = SIMILAR_MESSAGE; diff --git a/node_modules/jest-diff/build/diffLines.js b/node_modules/jest-diff/build/diffLines.js new file mode 100644 index 0000000..d18b960 --- /dev/null +++ b/node_modules/jest-diff/build/diffLines.js @@ -0,0 +1,193 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printDiffLines = + exports.diffLinesUnified2 = + exports.diffLinesUnified = + exports.diffLinesRaw = + void 0; +var _diffSequences = _interopRequireDefault(require('diff-sequences')); +var _cleanupSemantic = require('./cleanupSemantic'); +var _joinAlignedDiffs = require('./joinAlignedDiffs'); +var _normalizeDiffOptions = require('./normalizeDiffOptions'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const isEmptyString = lines => lines.length === 1 && lines[0].length === 0; +const countChanges = diffs => { + let a = 0; + let b = 0; + diffs.forEach(diff => { + switch (diff[0]) { + case _cleanupSemantic.DIFF_DELETE: + a += 1; + break; + case _cleanupSemantic.DIFF_INSERT: + b += 1; + break; + } + }); + return { + a, + b + }; +}; +const printAnnotation = ( + { + aAnnotation, + aColor, + aIndicator, + bAnnotation, + bColor, + bIndicator, + includeChangeCounts, + omitAnnotationLines + }, + changeCounts +) => { + if (omitAnnotationLines) { + return ''; + } + let aRest = ''; + let bRest = ''; + if (includeChangeCounts) { + const aCount = String(changeCounts.a); + const bCount = String(changeCounts.b); + + // Padding right aligns the ends of the annotations. + const baAnnotationLengthDiff = bAnnotation.length - aAnnotation.length; + const aAnnotationPadding = ' '.repeat(Math.max(0, baAnnotationLengthDiff)); + const bAnnotationPadding = ' '.repeat(Math.max(0, -baAnnotationLengthDiff)); + + // Padding left aligns the ends of the counts. + const baCountLengthDiff = bCount.length - aCount.length; + const aCountPadding = ' '.repeat(Math.max(0, baCountLengthDiff)); + const bCountPadding = ' '.repeat(Math.max(0, -baCountLengthDiff)); + aRest = `${aAnnotationPadding} ${aIndicator} ${aCountPadding}${aCount}`; + bRest = `${bAnnotationPadding} ${bIndicator} ${bCountPadding}${bCount}`; + } + const a = `${aIndicator} ${aAnnotation}${aRest}`; + const b = `${bIndicator} ${bAnnotation}${bRest}`; + return `${aColor(a)}\n${bColor(b)}\n\n`; +}; +const printDiffLines = (diffs, options) => + printAnnotation(options, countChanges(diffs)) + + (options.expand + ? (0, _joinAlignedDiffs.joinAlignedDiffsExpand)(diffs, options) + : (0, _joinAlignedDiffs.joinAlignedDiffsNoExpand)(diffs, options)); + +// Compare two arrays of strings line-by-line. Format as comparison lines. +exports.printDiffLines = printDiffLines; +const diffLinesUnified = (aLines, bLines, options) => + printDiffLines( + diffLinesRaw( + isEmptyString(aLines) ? [] : aLines, + isEmptyString(bLines) ? [] : bLines + ), + (0, _normalizeDiffOptions.normalizeDiffOptions)(options) + ); + +// Given two pairs of arrays of strings: +// Compare the pair of comparison arrays line-by-line. +// Format the corresponding lines in the pair of displayable arrays. +exports.diffLinesUnified = diffLinesUnified; +const diffLinesUnified2 = ( + aLinesDisplay, + bLinesDisplay, + aLinesCompare, + bLinesCompare, + options +) => { + if (isEmptyString(aLinesDisplay) && isEmptyString(aLinesCompare)) { + aLinesDisplay = []; + aLinesCompare = []; + } + if (isEmptyString(bLinesDisplay) && isEmptyString(bLinesCompare)) { + bLinesDisplay = []; + bLinesCompare = []; + } + if ( + aLinesDisplay.length !== aLinesCompare.length || + bLinesDisplay.length !== bLinesCompare.length + ) { + // Fall back to diff of display lines. + return diffLinesUnified(aLinesDisplay, bLinesDisplay, options); + } + const diffs = diffLinesRaw(aLinesCompare, bLinesCompare); + + // Replace comparison lines with displayable lines. + let aIndex = 0; + let bIndex = 0; + diffs.forEach(diff => { + switch (diff[0]) { + case _cleanupSemantic.DIFF_DELETE: + diff[1] = aLinesDisplay[aIndex]; + aIndex += 1; + break; + case _cleanupSemantic.DIFF_INSERT: + diff[1] = bLinesDisplay[bIndex]; + bIndex += 1; + break; + default: + diff[1] = bLinesDisplay[bIndex]; + aIndex += 1; + bIndex += 1; + } + }); + return printDiffLines( + diffs, + (0, _normalizeDiffOptions.normalizeDiffOptions)(options) + ); +}; + +// Compare two arrays of strings line-by-line. +exports.diffLinesUnified2 = diffLinesUnified2; +const diffLinesRaw = (aLines, bLines) => { + const aLength = aLines.length; + const bLength = bLines.length; + const isCommon = (aIndex, bIndex) => aLines[aIndex] === bLines[bIndex]; + const diffs = []; + let aIndex = 0; + let bIndex = 0; + const foundSubsequence = (nCommon, aCommon, bCommon) => { + for (; aIndex !== aCommon; aIndex += 1) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_DELETE, aLines[aIndex]) + ); + } + for (; bIndex !== bCommon; bIndex += 1) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_INSERT, bLines[bIndex]) + ); + } + for (; nCommon !== 0; nCommon -= 1, aIndex += 1, bIndex += 1) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_EQUAL, bLines[bIndex]) + ); + } + }; + (0, _diffSequences.default)(aLength, bLength, isCommon, foundSubsequence); + + // After the last common subsequence, push remaining change items. + for (; aIndex !== aLength; aIndex += 1) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_DELETE, aLines[aIndex]) + ); + } + for (; bIndex !== bLength; bIndex += 1) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_INSERT, bLines[bIndex]) + ); + } + return diffs; +}; +exports.diffLinesRaw = diffLinesRaw; diff --git a/node_modules/jest-diff/build/diffStrings.js b/node_modules/jest-diff/build/diffStrings.js new file mode 100644 index 0000000..0a6af5c --- /dev/null +++ b/node_modules/jest-diff/build/diffStrings.js @@ -0,0 +1,66 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _diffSequences = _interopRequireDefault(require('diff-sequences')); +var _cleanupSemantic = require('./cleanupSemantic'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const diffStrings = (a, b) => { + const isCommon = (aIndex, bIndex) => a[aIndex] === b[bIndex]; + let aIndex = 0; + let bIndex = 0; + const diffs = []; + const foundSubsequence = (nCommon, aCommon, bCommon) => { + if (aIndex !== aCommon) { + diffs.push( + new _cleanupSemantic.Diff( + _cleanupSemantic.DIFF_DELETE, + a.slice(aIndex, aCommon) + ) + ); + } + if (bIndex !== bCommon) { + diffs.push( + new _cleanupSemantic.Diff( + _cleanupSemantic.DIFF_INSERT, + b.slice(bIndex, bCommon) + ) + ); + } + aIndex = aCommon + nCommon; // number of characters compared in a + bIndex = bCommon + nCommon; // number of characters compared in b + diffs.push( + new _cleanupSemantic.Diff( + _cleanupSemantic.DIFF_EQUAL, + b.slice(bCommon, bIndex) + ) + ); + }; + (0, _diffSequences.default)(a.length, b.length, isCommon, foundSubsequence); + + // After the last common subsequence, push remaining change items. + if (aIndex !== a.length) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_DELETE, a.slice(aIndex)) + ); + } + if (bIndex !== b.length) { + diffs.push( + new _cleanupSemantic.Diff(_cleanupSemantic.DIFF_INSERT, b.slice(bIndex)) + ); + } + return diffs; +}; +var _default = diffStrings; +exports.default = _default; diff --git a/node_modules/jest-diff/build/getAlignedDiffs.js b/node_modules/jest-diff/build/getAlignedDiffs.js new file mode 100644 index 0000000..a090134 --- /dev/null +++ b/node_modules/jest-diff/build/getAlignedDiffs.js @@ -0,0 +1,223 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _cleanupSemantic = require('./cleanupSemantic'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Given change op and array of diffs, return concatenated string: +// * include common strings +// * include change strings which have argument op with changeColor +// * exclude change strings which have opposite op +const concatenateRelevantDiffs = (op, diffs, changeColor) => + diffs.reduce( + (reduced, diff) => + reduced + + (diff[0] === _cleanupSemantic.DIFF_EQUAL + ? diff[1] + : diff[0] === op && diff[1].length !== 0 // empty if change is newline + ? changeColor(diff[1]) + : ''), + '' + ); + +// Encapsulate change lines until either a common newline or the end. +class ChangeBuffer { + op; + line; // incomplete line + lines; // complete lines + changeColor; + constructor(op, changeColor) { + this.op = op; + this.line = []; + this.lines = []; + this.changeColor = changeColor; + } + pushSubstring(substring) { + this.pushDiff(new _cleanupSemantic.Diff(this.op, substring)); + } + pushLine() { + // Assume call only if line has at least one diff, + // therefore an empty line must have a diff which has an empty string. + + // If line has multiple diffs, then assume it has a common diff, + // therefore change diffs have change color; + // otherwise then it has line color only. + this.lines.push( + this.line.length !== 1 + ? new _cleanupSemantic.Diff( + this.op, + concatenateRelevantDiffs(this.op, this.line, this.changeColor) + ) + : this.line[0][0] === this.op + ? this.line[0] // can use instance + : new _cleanupSemantic.Diff(this.op, this.line[0][1]) // was common diff + ); + + this.line.length = 0; + } + isLineEmpty() { + return this.line.length === 0; + } + + // Minor input to buffer. + pushDiff(diff) { + this.line.push(diff); + } + + // Main input to buffer. + align(diff) { + const string = diff[1]; + if (string.includes('\n')) { + const substrings = string.split('\n'); + const iLast = substrings.length - 1; + substrings.forEach((substring, i) => { + if (i < iLast) { + // The first substring completes the current change line. + // A middle substring is a change line. + this.pushSubstring(substring); + this.pushLine(); + } else if (substring.length !== 0) { + // The last substring starts a change line, if it is not empty. + // Important: This non-empty condition also automatically omits + // the newline appended to the end of expected and received strings. + this.pushSubstring(substring); + } + }); + } else { + // Append non-multiline string to current change line. + this.pushDiff(diff); + } + } + + // Output from buffer. + moveLinesTo(lines) { + if (!this.isLineEmpty()) { + this.pushLine(); + } + lines.push(...this.lines); + this.lines.length = 0; + } +} + +// Encapsulate common and change lines. +class CommonBuffer { + deleteBuffer; + insertBuffer; + lines; + constructor(deleteBuffer, insertBuffer) { + this.deleteBuffer = deleteBuffer; + this.insertBuffer = insertBuffer; + this.lines = []; + } + pushDiffCommonLine(diff) { + this.lines.push(diff); + } + pushDiffChangeLines(diff) { + const isDiffEmpty = diff[1].length === 0; + + // An empty diff string is redundant, unless a change line is empty. + if (!isDiffEmpty || this.deleteBuffer.isLineEmpty()) { + this.deleteBuffer.pushDiff(diff); + } + if (!isDiffEmpty || this.insertBuffer.isLineEmpty()) { + this.insertBuffer.pushDiff(diff); + } + } + flushChangeLines() { + this.deleteBuffer.moveLinesTo(this.lines); + this.insertBuffer.moveLinesTo(this.lines); + } + + // Input to buffer. + align(diff) { + const op = diff[0]; + const string = diff[1]; + if (string.includes('\n')) { + const substrings = string.split('\n'); + const iLast = substrings.length - 1; + substrings.forEach((substring, i) => { + if (i === 0) { + const subdiff = new _cleanupSemantic.Diff(op, substring); + if ( + this.deleteBuffer.isLineEmpty() && + this.insertBuffer.isLineEmpty() + ) { + // If both current change lines are empty, + // then the first substring is a common line. + this.flushChangeLines(); + this.pushDiffCommonLine(subdiff); + } else { + // If either current change line is non-empty, + // then the first substring completes the change lines. + this.pushDiffChangeLines(subdiff); + this.flushChangeLines(); + } + } else if (i < iLast) { + // A middle substring is a common line. + this.pushDiffCommonLine(new _cleanupSemantic.Diff(op, substring)); + } else if (substring.length !== 0) { + // The last substring starts a change line, if it is not empty. + // Important: This non-empty condition also automatically omits + // the newline appended to the end of expected and received strings. + this.pushDiffChangeLines(new _cleanupSemantic.Diff(op, substring)); + } + }); + } else { + // Append non-multiline string to current change lines. + // Important: It cannot be at the end following empty change lines, + // because newline appended to the end of expected and received strings. + this.pushDiffChangeLines(diff); + } + } + + // Output from buffer. + getLines() { + this.flushChangeLines(); + return this.lines; + } +} + +// Given diffs from expected and received strings, +// return new array of diffs split or joined into lines. +// +// To correctly align a change line at the end, the algorithm: +// * assumes that a newline was appended to the strings +// * omits the last newline from the output array +// +// Assume the function is not called: +// * if either expected or received is empty string +// * if neither expected nor received is multiline string +const getAlignedDiffs = (diffs, changeColor) => { + const deleteBuffer = new ChangeBuffer( + _cleanupSemantic.DIFF_DELETE, + changeColor + ); + const insertBuffer = new ChangeBuffer( + _cleanupSemantic.DIFF_INSERT, + changeColor + ); + const commonBuffer = new CommonBuffer(deleteBuffer, insertBuffer); + diffs.forEach(diff => { + switch (diff[0]) { + case _cleanupSemantic.DIFF_DELETE: + deleteBuffer.align(diff); + break; + case _cleanupSemantic.DIFF_INSERT: + insertBuffer.align(diff); + break; + default: + commonBuffer.align(diff); + } + }); + return commonBuffer.getLines(); +}; +var _default = getAlignedDiffs; +exports.default = _default; diff --git a/node_modules/jest-diff/build/index.d.ts b/node_modules/jest-diff/build/index.d.ts new file mode 100644 index 0000000..79bcffc --- /dev/null +++ b/node_modules/jest-diff/build/index.d.ts @@ -0,0 +1,93 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {CompareKeys} from 'pretty-format'; + +/** + * Class representing one diff tuple. + * Attempts to look like a two-element array (which is what this used to be). + * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. + * @param {string} text Text to be deleted, inserted, or retained. + * @constructor + */ +export declare class Diff { + 0: number; + 1: string; + constructor(op: number, text: string); +} + +export declare function diff( + a: any, + b: any, + options?: DiffOptions, +): string | null; + +/** + * The data structure representing a diff is an array of tuples: + * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] + * which means: delete 'Hello', add 'Goodbye' and keep ' world.' + */ +export declare var DIFF_DELETE: number; + +export declare var DIFF_EQUAL: number; + +export declare var DIFF_INSERT: number; + +export declare const diffLinesRaw: ( + aLines: Array, + bLines: Array, +) => Array; + +export declare const diffLinesUnified: ( + aLines: Array, + bLines: Array, + options?: DiffOptions, +) => string; + +export declare const diffLinesUnified2: ( + aLinesDisplay: Array, + bLinesDisplay: Array, + aLinesCompare: Array, + bLinesCompare: Array, + options?: DiffOptions, +) => string; + +export declare type DiffOptions = { + aAnnotation?: string; + aColor?: DiffOptionsColor; + aIndicator?: string; + bAnnotation?: string; + bColor?: DiffOptionsColor; + bIndicator?: string; + changeColor?: DiffOptionsColor; + changeLineTrailingSpaceColor?: DiffOptionsColor; + commonColor?: DiffOptionsColor; + commonIndicator?: string; + commonLineTrailingSpaceColor?: DiffOptionsColor; + contextLines?: number; + emptyFirstOrLastLinePlaceholder?: string; + expand?: boolean; + includeChangeCounts?: boolean; + omitAnnotationLines?: boolean; + patchColor?: DiffOptionsColor; + compareKeys?: CompareKeys; +}; + +export declare type DiffOptionsColor = (arg: string) => string; + +export declare const diffStringsRaw: ( + a: string, + b: string, + cleanup: boolean, +) => Array; + +export declare const diffStringsUnified: ( + a: string, + b: string, + options?: DiffOptions, +) => string; + +export {}; diff --git a/node_modules/jest-diff/build/index.js b/node_modules/jest-diff/build/index.js new file mode 100644 index 0000000..91997bf --- /dev/null +++ b/node_modules/jest-diff/build/index.js @@ -0,0 +1,226 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'DIFF_DELETE', { + enumerable: true, + get: function () { + return _cleanupSemantic.DIFF_DELETE; + } +}); +Object.defineProperty(exports, 'DIFF_EQUAL', { + enumerable: true, + get: function () { + return _cleanupSemantic.DIFF_EQUAL; + } +}); +Object.defineProperty(exports, 'DIFF_INSERT', { + enumerable: true, + get: function () { + return _cleanupSemantic.DIFF_INSERT; + } +}); +Object.defineProperty(exports, 'Diff', { + enumerable: true, + get: function () { + return _cleanupSemantic.Diff; + } +}); +exports.diff = diff; +Object.defineProperty(exports, 'diffLinesRaw', { + enumerable: true, + get: function () { + return _diffLines.diffLinesRaw; + } +}); +Object.defineProperty(exports, 'diffLinesUnified', { + enumerable: true, + get: function () { + return _diffLines.diffLinesUnified; + } +}); +Object.defineProperty(exports, 'diffLinesUnified2', { + enumerable: true, + get: function () { + return _diffLines.diffLinesUnified2; + } +}); +Object.defineProperty(exports, 'diffStringsRaw', { + enumerable: true, + get: function () { + return _printDiffs.diffStringsRaw; + } +}); +Object.defineProperty(exports, 'diffStringsUnified', { + enumerable: true, + get: function () { + return _printDiffs.diffStringsUnified; + } +}); +var _chalk = _interopRequireDefault(require('chalk')); +var _jestGetType = require('jest-get-type'); +var _prettyFormat = require('pretty-format'); +var _cleanupSemantic = require('./cleanupSemantic'); +var _constants = require('./constants'); +var _diffLines = require('./diffLines'); +var _normalizeDiffOptions = require('./normalizeDiffOptions'); +var _printDiffs = require('./printDiffs'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +const getCommonMessage = (message, options) => { + const {commonColor} = (0, _normalizeDiffOptions.normalizeDiffOptions)( + options + ); + return commonColor(message); +}; +const { + AsymmetricMatcher, + DOMCollection, + DOMElement, + Immutable, + ReactElement, + ReactTestComponent +} = _prettyFormat.plugins; +const PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher +]; +const FORMAT_OPTIONS = { + plugins: PLUGINS +}; +const FALLBACK_FORMAT_OPTIONS = { + callToJSON: false, + maxDepth: 10, + plugins: PLUGINS +}; + +// Generate a string that will highlight the difference between two values +// with green and red. (similar to how github does code diffing) +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function diff(a, b, options) { + if (Object.is(a, b)) { + return getCommonMessage(_constants.NO_DIFF_MESSAGE, options); + } + const aType = (0, _jestGetType.getType)(a); + let expectedType = aType; + let omitDifference = false; + if (aType === 'object' && typeof a.asymmetricMatch === 'function') { + if (a.$$typeof !== Symbol.for('jest.asymmetricMatcher')) { + // Do not know expected type of user-defined asymmetric matcher. + return null; + } + if (typeof a.getExpectedType !== 'function') { + // For example, expect.anything() matches either null or undefined + return null; + } + expectedType = a.getExpectedType(); + // Primitive types boolean and number omit difference below. + // For example, omit difference for expect.stringMatching(regexp) + omitDifference = expectedType === 'string'; + } + if (expectedType !== (0, _jestGetType.getType)(b)) { + return ( + ' Comparing two different types of values.' + + ` Expected ${_chalk.default.green(expectedType)} but ` + + `received ${_chalk.default.red((0, _jestGetType.getType)(b))}.` + ); + } + if (omitDifference) { + return null; + } + switch (aType) { + case 'string': + return (0, _diffLines.diffLinesUnified)( + a.split('\n'), + b.split('\n'), + options + ); + case 'boolean': + case 'number': + return comparePrimitive(a, b, options); + case 'map': + return compareObjects(sortMap(a), sortMap(b), options); + case 'set': + return compareObjects(sortSet(a), sortSet(b), options); + default: + return compareObjects(a, b, options); + } +} +function comparePrimitive(a, b, options) { + const aFormat = (0, _prettyFormat.format)(a, FORMAT_OPTIONS); + const bFormat = (0, _prettyFormat.format)(b, FORMAT_OPTIONS); + return aFormat === bFormat + ? getCommonMessage(_constants.NO_DIFF_MESSAGE, options) + : (0, _diffLines.diffLinesUnified)( + aFormat.split('\n'), + bFormat.split('\n'), + options + ); +} +function sortMap(map) { + return new Map(Array.from(map.entries()).sort()); +} +function sortSet(set) { + return new Set(Array.from(set.values()).sort()); +} +function compareObjects(a, b, options) { + let difference; + let hasThrown = false; + try { + const formatOptions = getFormatOptions(FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + } catch { + hasThrown = true; + } + const noDiffMessage = getCommonMessage(_constants.NO_DIFF_MESSAGE, options); + // If the comparison yields no results, compare again but this time + // without calling `toJSON`. It's also possible that toJSON might throw. + if (difference === undefined || difference === noDiffMessage) { + const formatOptions = getFormatOptions(FALLBACK_FORMAT_OPTIONS, options); + difference = getObjectsDifference(a, b, formatOptions, options); + if (difference !== noDiffMessage && !hasThrown) { + difference = `${getCommonMessage( + _constants.SIMILAR_MESSAGE, + options + )}\n\n${difference}`; + } + } + return difference; +} +function getFormatOptions(formatOptions, options) { + const {compareKeys} = (0, _normalizeDiffOptions.normalizeDiffOptions)( + options + ); + return { + ...formatOptions, + compareKeys + }; +} +function getObjectsDifference(a, b, formatOptions, options) { + const formatOptionsZeroIndent = { + ...formatOptions, + indent: 0 + }; + const aCompare = (0, _prettyFormat.format)(a, formatOptionsZeroIndent); + const bCompare = (0, _prettyFormat.format)(b, formatOptionsZeroIndent); + if (aCompare === bCompare) { + return getCommonMessage(_constants.NO_DIFF_MESSAGE, options); + } else { + const aDisplay = (0, _prettyFormat.format)(a, formatOptions); + const bDisplay = (0, _prettyFormat.format)(b, formatOptions); + return (0, _diffLines.diffLinesUnified2)( + aDisplay.split('\n'), + bDisplay.split('\n'), + aCompare.split('\n'), + bCompare.split('\n'), + options + ); + } +} diff --git a/node_modules/jest-diff/build/joinAlignedDiffs.js b/node_modules/jest-diff/build/joinAlignedDiffs.js new file mode 100644 index 0000000..c143b9f --- /dev/null +++ b/node_modules/jest-diff/build/joinAlignedDiffs.js @@ -0,0 +1,271 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.joinAlignedDiffsNoExpand = exports.joinAlignedDiffsExpand = void 0; +var _cleanupSemantic = require('./cleanupSemantic'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const formatTrailingSpaces = (line, trailingSpaceFormatter) => + line.replace(/\s+$/, match => trailingSpaceFormatter(match)); +const printDiffLine = ( + line, + isFirstOrLast, + color, + indicator, + trailingSpaceFormatter, + emptyFirstOrLastLinePlaceholder +) => + line.length !== 0 + ? color( + `${indicator} ${formatTrailingSpaces(line, trailingSpaceFormatter)}` + ) + : indicator !== ' ' + ? color(indicator) + : isFirstOrLast && emptyFirstOrLastLinePlaceholder.length !== 0 + ? color(`${indicator} ${emptyFirstOrLastLinePlaceholder}`) + : ''; +const printDeleteLine = ( + line, + isFirstOrLast, + { + aColor, + aIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + } +) => + printDiffLine( + line, + isFirstOrLast, + aColor, + aIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + ); +const printInsertLine = ( + line, + isFirstOrLast, + { + bColor, + bIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + } +) => + printDiffLine( + line, + isFirstOrLast, + bColor, + bIndicator, + changeLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + ); +const printCommonLine = ( + line, + isFirstOrLast, + { + commonColor, + commonIndicator, + commonLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + } +) => + printDiffLine( + line, + isFirstOrLast, + commonColor, + commonIndicator, + commonLineTrailingSpaceColor, + emptyFirstOrLastLinePlaceholder + ); + +// In GNU diff format, indexes are one-based instead of zero-based. +const createPatchMark = (aStart, aEnd, bStart, bEnd, {patchColor}) => + patchColor( + `@@ -${aStart + 1},${aEnd - aStart} +${bStart + 1},${bEnd - bStart} @@` + ); + +// jest --no-expand +// +// Given array of aligned strings with inverse highlight formatting, +// return joined lines with diff formatting (and patch marks, if needed). +const joinAlignedDiffsNoExpand = (diffs, options) => { + const iLength = diffs.length; + const nContextLines = options.contextLines; + const nContextLines2 = nContextLines + nContextLines; + + // First pass: count output lines and see if it has patches. + let jLength = iLength; + let hasExcessAtStartOrEnd = false; + let nExcessesBetweenChanges = 0; + let i = 0; + while (i !== iLength) { + const iStart = i; + while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_EQUAL) { + i += 1; + } + if (iStart !== i) { + if (iStart === 0) { + // at start + if (i > nContextLines) { + jLength -= i - nContextLines; // subtract excess common lines + hasExcessAtStartOrEnd = true; + } + } else if (i === iLength) { + // at end + const n = i - iStart; + if (n > nContextLines) { + jLength -= n - nContextLines; // subtract excess common lines + hasExcessAtStartOrEnd = true; + } + } else { + // between changes + const n = i - iStart; + if (n > nContextLines2) { + jLength -= n - nContextLines2; // subtract excess common lines + nExcessesBetweenChanges += 1; + } + } + } + while (i !== iLength && diffs[i][0] !== _cleanupSemantic.DIFF_EQUAL) { + i += 1; + } + } + const hasPatch = nExcessesBetweenChanges !== 0 || hasExcessAtStartOrEnd; + if (nExcessesBetweenChanges !== 0) { + jLength += nExcessesBetweenChanges + 1; // add patch lines + } else if (hasExcessAtStartOrEnd) { + jLength += 1; // add patch line + } + + const jLast = jLength - 1; + const lines = []; + let jPatchMark = 0; // index of placeholder line for current patch mark + if (hasPatch) { + lines.push(''); // placeholder line for first patch mark + } + + // Indexes of expected or received lines in current patch: + let aStart = 0; + let bStart = 0; + let aEnd = 0; + let bEnd = 0; + const pushCommonLine = line => { + const j = lines.length; + lines.push(printCommonLine(line, j === 0 || j === jLast, options)); + aEnd += 1; + bEnd += 1; + }; + const pushDeleteLine = line => { + const j = lines.length; + lines.push(printDeleteLine(line, j === 0 || j === jLast, options)); + aEnd += 1; + }; + const pushInsertLine = line => { + const j = lines.length; + lines.push(printInsertLine(line, j === 0 || j === jLast, options)); + bEnd += 1; + }; + + // Second pass: push lines with diff formatting (and patch marks, if needed). + i = 0; + while (i !== iLength) { + let iStart = i; + while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_EQUAL) { + i += 1; + } + if (iStart !== i) { + if (iStart === 0) { + // at beginning + if (i > nContextLines) { + iStart = i - nContextLines; + aStart = iStart; + bStart = iStart; + aEnd = aStart; + bEnd = bStart; + } + for (let iCommon = iStart; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else if (i === iLength) { + // at end + const iEnd = i - iStart > nContextLines ? iStart + nContextLines : i; + for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else { + // between changes + const nCommon = i - iStart; + if (nCommon > nContextLines2) { + const iEnd = iStart + nContextLines; + for (let iCommon = iStart; iCommon !== iEnd; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + lines[jPatchMark] = createPatchMark( + aStart, + aEnd, + bStart, + bEnd, + options + ); + jPatchMark = lines.length; + lines.push(''); // placeholder line for next patch mark + + const nOmit = nCommon - nContextLines2; + aStart = aEnd + nOmit; + bStart = bEnd + nOmit; + aEnd = aStart; + bEnd = bStart; + for (let iCommon = i - nContextLines; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } else { + for (let iCommon = iStart; iCommon !== i; iCommon += 1) { + pushCommonLine(diffs[iCommon][1]); + } + } + } + } + while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_DELETE) { + pushDeleteLine(diffs[i][1]); + i += 1; + } + while (i !== iLength && diffs[i][0] === _cleanupSemantic.DIFF_INSERT) { + pushInsertLine(diffs[i][1]); + i += 1; + } + } + if (hasPatch) { + lines[jPatchMark] = createPatchMark(aStart, aEnd, bStart, bEnd, options); + } + return lines.join('\n'); +}; + +// jest --expand +// +// Given array of aligned strings with inverse highlight formatting, +// return joined lines with diff formatting. +exports.joinAlignedDiffsNoExpand = joinAlignedDiffsNoExpand; +const joinAlignedDiffsExpand = (diffs, options) => + diffs + .map((diff, i, diffs) => { + const line = diff[1]; + const isFirstOrLast = i === 0 || i === diffs.length - 1; + switch (diff[0]) { + case _cleanupSemantic.DIFF_DELETE: + return printDeleteLine(line, isFirstOrLast, options); + case _cleanupSemantic.DIFF_INSERT: + return printInsertLine(line, isFirstOrLast, options); + default: + return printCommonLine(line, isFirstOrLast, options); + } + }) + .join('\n'); +exports.joinAlignedDiffsExpand = joinAlignedDiffsExpand; diff --git a/node_modules/jest-diff/build/normalizeDiffOptions.js b/node_modules/jest-diff/build/normalizeDiffOptions.js new file mode 100644 index 0000000..52c38d2 --- /dev/null +++ b/node_modules/jest-diff/build/normalizeDiffOptions.js @@ -0,0 +1,59 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.normalizeDiffOptions = exports.noColor = void 0; +var _chalk = _interopRequireDefault(require('chalk')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const noColor = string => string; +exports.noColor = noColor; +const DIFF_CONTEXT_DEFAULT = 5; +const OPTIONS_DEFAULT = { + aAnnotation: 'Expected', + aColor: _chalk.default.green, + aIndicator: '-', + bAnnotation: 'Received', + bColor: _chalk.default.red, + bIndicator: '+', + changeColor: _chalk.default.inverse, + changeLineTrailingSpaceColor: noColor, + commonColor: _chalk.default.dim, + commonIndicator: ' ', + commonLineTrailingSpaceColor: noColor, + compareKeys: undefined, + contextLines: DIFF_CONTEXT_DEFAULT, + emptyFirstOrLastLinePlaceholder: '', + expand: true, + includeChangeCounts: false, + omitAnnotationLines: false, + patchColor: _chalk.default.yellow +}; +const getCompareKeys = compareKeys => + compareKeys && typeof compareKeys === 'function' + ? compareKeys + : OPTIONS_DEFAULT.compareKeys; +const getContextLines = contextLines => + typeof contextLines === 'number' && + Number.isSafeInteger(contextLines) && + contextLines >= 0 + ? contextLines + : DIFF_CONTEXT_DEFAULT; + +// Pure function returns options with all properties. +const normalizeDiffOptions = (options = {}) => ({ + ...OPTIONS_DEFAULT, + ...options, + compareKeys: getCompareKeys(options.compareKeys), + contextLines: getContextLines(options.contextLines) +}); +exports.normalizeDiffOptions = normalizeDiffOptions; diff --git a/node_modules/jest-diff/build/printDiffs.js b/node_modules/jest-diff/build/printDiffs.js new file mode 100644 index 0000000..9d7874c --- /dev/null +++ b/node_modules/jest-diff/build/printDiffs.js @@ -0,0 +1,79 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.diffStringsUnified = exports.diffStringsRaw = void 0; +var _cleanupSemantic = require('./cleanupSemantic'); +var _diffLines = require('./diffLines'); +var _diffStrings = _interopRequireDefault(require('./diffStrings')); +var _getAlignedDiffs = _interopRequireDefault(require('./getAlignedDiffs')); +var _normalizeDiffOptions = require('./normalizeDiffOptions'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const hasCommonDiff = (diffs, isMultiline) => { + if (isMultiline) { + // Important: Ignore common newline that was appended to multiline strings! + const iLast = diffs.length - 1; + return diffs.some( + (diff, i) => + diff[0] === _cleanupSemantic.DIFF_EQUAL && + (i !== iLast || diff[1] !== '\n') + ); + } + return diffs.some(diff => diff[0] === _cleanupSemantic.DIFF_EQUAL); +}; + +// Compare two strings character-by-character. +// Format as comparison lines in which changed substrings have inverse colors. +const diffStringsUnified = (a, b, options) => { + if (a !== b && a.length !== 0 && b.length !== 0) { + const isMultiline = a.includes('\n') || b.includes('\n'); + + // getAlignedDiffs assumes that a newline was appended to the strings. + const diffs = diffStringsRaw( + isMultiline ? `${a}\n` : a, + isMultiline ? `${b}\n` : b, + true // cleanupSemantic + ); + + if (hasCommonDiff(diffs, isMultiline)) { + const optionsNormalized = (0, _normalizeDiffOptions.normalizeDiffOptions)( + options + ); + const lines = (0, _getAlignedDiffs.default)( + diffs, + optionsNormalized.changeColor + ); + return (0, _diffLines.printDiffLines)(lines, optionsNormalized); + } + } + + // Fall back to line-by-line diff. + return (0, _diffLines.diffLinesUnified)( + a.split('\n'), + b.split('\n'), + options + ); +}; + +// Compare two strings character-by-character. +// Optionally clean up small common substrings, also known as chaff. +exports.diffStringsUnified = diffStringsUnified; +const diffStringsRaw = (a, b, cleanup) => { + const diffs = (0, _diffStrings.default)(a, b); + if (cleanup) { + (0, _cleanupSemantic.cleanupSemantic)(diffs); // impure function + } + + return diffs; +}; +exports.diffStringsRaw = diffStringsRaw; diff --git a/node_modules/jest-diff/build/types.js b/node_modules/jest-diff/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-diff/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-diff/package.json b/node_modules/jest-diff/package.json new file mode 100644 index 0000000..b349377 --- /dev/null +++ b/node_modules/jest-diff/package.json @@ -0,0 +1,36 @@ +{ + "name": "jest-diff", + "version": "29.2.1", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-diff" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "chalk": "^4.0.0", + "diff-sequences": "^29.2.0", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.2.1" + }, + "devDependencies": { + "@jest/test-utils": "^29.2.1", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "4551c0fdd4d25b7206824957c7bcc6baf61e63bf" +} diff --git a/node_modules/jest-docblock/LICENSE b/node_modules/jest-docblock/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-docblock/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-docblock/README.md b/node_modules/jest-docblock/README.md new file mode 100644 index 0000000..ba3fc7b --- /dev/null +++ b/node_modules/jest-docblock/README.md @@ -0,0 +1,108 @@ +# jest-docblock + +`jest-docblock` is a package that can extract and parse a specially-formatted comment called a "docblock" at the top of a file. + +A docblock looks like this: + +```js +/** + * Stuff goes here! + */ +``` + +Docblocks can contain pragmas, which are words prefixed by `@`: + +```js +/** + * Pragma incoming! + * + * @flow + */ +``` + +Pragmas can also take arguments: + +```js +/** + * Check this out: + * + * @myPragma it is so cool + */ +``` + +`jest-docblock` can: + +- extract the docblock from some code as a string +- parse a docblock string's pragmas into an object +- print an object and some comments back to a string + +## Installation + +```sh +# with yarn +$ yarn add jest-docblock +# with npm +$ npm install jest-docblock +``` + +## Usage + +```js +const code = ` +/** + * Everything is awesome! + * + * @everything is:awesome + * @flow + */ + + export const everything = Object.create(null); + export default function isAwesome(something) { + return something === everything; + } +`; + +const { + extract, + strip, + parse, + parseWithComments, + print, +} = require('jest-docblock'); + +const docblock = extract(code); +console.log(docblock); // "/**\n * Everything is awesome!\n * \n * @everything is:awesome\n * @flow\n */" + +const stripped = strip(code); +console.log(stripped); // "export const everything = Object.create(null);\n export default function isAwesome(something) {\n return something === everything;\n }" + +const pragmas = parse(docblock); +console.log(pragmas); // { everything: "is:awesome", flow: "" } + +const parsed = parseWithComments(docblock); +console.log(parsed); // { comments: "Everything is awesome!", pragmas: { everything: "is:awesome", flow: "" } } + +console.log(print({pragmas, comments: 'hi!'})); // /**\n * hi!\n *\n * @everything is:awesome\n * @flow\n */; +``` + +## API Documentation + +### `extract(contents: string): string` + +Extracts a docblock from some file contents. Returns the docblock contained in `contents`. If `contents` did not contain a docblock, it will return the empty string (`""`). + +### `strip(contents: string): string` + +Strips the top docblock from a file and return the result. If a file does not have a docblock at the top, then return the file unchanged. + +### `parse(docblock: string): {[key: string]: string | string[] }` + +Parses the pragmas in a docblock string into an object whose keys are the pragma tags and whose values are the arguments to those pragmas. + +### `parseWithComments(docblock: string): { comments: string, pragmas: {[key: string]: string | string[]} }` + +Similar to `parse` except this method also returns the comments from the docblock. Useful when used with `print()`. + +### `print({ comments?: string, pragmas?: {[key: string]: string | string[]} }): string` + +Prints an object of key-value pairs back into a docblock. If `comments` are provided, they will be positioned on the top of the docblock. diff --git a/node_modules/jest-docblock/build/index.d.ts b/node_modules/jest-docblock/build/index.d.ts new file mode 100644 index 0000000..3c25df5 --- /dev/null +++ b/node_modules/jest-docblock/build/index.d.ts @@ -0,0 +1,29 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare function extract(contents: string): string; + +export declare function parse(docblock: string): Pragmas; + +export declare function parseWithComments(docblock: string): { + comments: string; + pragmas: Pragmas; +}; + +declare type Pragmas = Record>; + +declare function print_2({ + comments, + pragmas, +}: { + comments?: string; + pragmas?: Pragmas; +}): string; +export {print_2 as print}; + +export declare function strip(contents: string): string; + +export {}; diff --git a/node_modules/jest-docblock/build/index.js b/node_modules/jest-docblock/build/index.js new file mode 100644 index 0000000..9c0d82f --- /dev/null +++ b/node_modules/jest-docblock/build/index.js @@ -0,0 +1,131 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.extract = extract; +exports.parse = parse; +exports.parseWithComments = parseWithComments; +exports.print = print; +exports.strip = strip; +function _os() { + const data = require('os'); + _os = function () { + return data; + }; + return data; +} +function _detectNewline() { + const data = _interopRequireDefault(require('detect-newline')); + _detectNewline = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const commentEndRe = /\*\/$/; +const commentStartRe = /^\/\*\*?/; +const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/; +const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g; +const ltrimNewlineRe = /^(\r?\n)+/; +const multilineRe = + /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g; +const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; +const stringStartRe = /(\r?\n|^) *\* ?/g; +const STRING_ARRAY = []; +function extract(contents) { + const match = contents.match(docblockRe); + return match ? match[0].trimLeft() : ''; +} +function strip(contents) { + const match = contents.match(docblockRe); + return match && match[0] ? contents.substring(match[0].length) : contents; +} +function parse(docblock) { + return parseWithComments(docblock).pragmas; +} +function parseWithComments(docblock) { + const line = (0, _detectNewline().default)(docblock) ?? _os().EOL; + docblock = docblock + .replace(commentStartRe, '') + .replace(commentEndRe, '') + .replace(stringStartRe, '$1'); + + // Normalize multi-line directives + let prev = ''; + while (prev !== docblock) { + prev = docblock; + docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`); + } + docblock = docblock.replace(ltrimNewlineRe, '').trimRight(); + const result = Object.create(null); + const comments = docblock + .replace(propertyRe, '') + .replace(ltrimNewlineRe, '') + .trimRight(); + let match; + while ((match = propertyRe.exec(docblock))) { + // strip linecomments from pragmas + const nextPragma = match[2].replace(lineCommentRe, ''); + if ( + typeof result[match[1]] === 'string' || + Array.isArray(result[match[1]]) + ) { + result[match[1]] = STRING_ARRAY.concat(result[match[1]], nextPragma); + } else { + result[match[1]] = nextPragma; + } + } + return { + comments, + pragmas: result + }; +} +function print({comments = '', pragmas = {}}) { + const line = (0, _detectNewline().default)(comments) ?? _os().EOL; + const head = '/**'; + const start = ' *'; + const tail = ' */'; + const keys = Object.keys(pragmas); + const printedObject = keys + .map(key => printKeyValues(key, pragmas[key])) + .reduce((arr, next) => arr.concat(next), []) + .map(keyValue => `${start} ${keyValue}${line}`) + .join(''); + if (!comments) { + if (keys.length === 0) { + return ''; + } + if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) { + const value = pragmas[keys[0]]; + return `${head} ${printKeyValues(keys[0], value)[0]}${tail}`; + } + } + const printedComments = + comments + .split(line) + .map(textLine => `${start} ${textLine}`) + .join(line) + line; + return ( + head + + line + + (comments ? printedComments : '') + + (comments && keys.length ? start + line : '') + + printedObject + + tail + ); +} +function printKeyValues(key, valueOrArray) { + return STRING_ARRAY.concat(valueOrArray).map(value => + `@${key} ${value}`.trim() + ); +} diff --git a/node_modules/jest-docblock/package.json b/node_modules/jest-docblock/package.json new file mode 100644 index 0000000..c1e60b8 --- /dev/null +++ b/node_modules/jest-docblock/package.json @@ -0,0 +1,32 @@ +{ + "name": "jest-docblock", + "version": "29.2.0", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-docblock" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "detect-newline": "^3.0.0" + }, + "devDependencies": { + "@types/node": "*" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "ee5b37a4f4433afcfffb0356cea47739d8092287" +} diff --git a/node_modules/jest-each/LICENSE b/node_modules/jest-each/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-each/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-each/README.md b/node_modules/jest-each/README.md new file mode 100644 index 0000000..da3b2ad --- /dev/null +++ b/node_modules/jest-each/README.md @@ -0,0 +1,548 @@ +
+

jest-each

+ Jest Parameterised Testing +
+ +
+ +[![version](https://img.shields.io/npm/v/jest-each.svg?style=flat-square)](https://www.npmjs.com/package/jest-each) [![downloads](https://img.shields.io/npm/dm/jest-each.svg?style=flat-square)](http://npm-stat.com/charts.html?package=jest-each&from=2017-03-21) [![MIT License](https://img.shields.io/npm/l/jest-each.svg?style=flat-square)](https://github.com/facebook/jest/blob/main/LICENSE) + +A parameterised testing library for [Jest](https://jestjs.io/) inspired by [mocha-each](https://github.com/ryym/mocha-each). + +jest-each allows you to provide multiple arguments to your `test`/`describe` which results in the test/suite being run once per row of parameters. + +## Features + +- `.test` to runs multiple tests with parameterised data + - Also under the alias: `.it` +- `.test.only` to only run the parameterised tests + - Also under the aliases: `.it.only` or `.fit` +- `.test.skip` to skip the parameterised tests + - Also under the aliases: `.it.skip` or `.xit` or `.xtest` +- `.test.concurrent` + - Also under the alias: `.it.concurrent` +- `.test.concurrent.only` + - Also under the alias: `.it.concurrent.only` +- `.test.concurrent.skip` + - Also under the alias: `.it.concurrent.skip` +- `.describe` to runs test suites with parameterised data +- `.describe.only` to only run the parameterised suite of tests + - Also under the aliases: `.fdescribe` +- `.describe.skip` to skip the parameterised suite of tests + - Also under the aliases: `.xdescribe` +- Asynchronous tests with `done` +- Unique test titles with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): + - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). + - `%s`- String. + - `%d`- Number. + - `%i` - Integer. + - `%f` - Floating point value. + - `%j` - JSON. + - `%o` - Object. + - `%#` - Index of the test case. + - `%%` - single percent sign ('%'). This does not consume an argument. +- Unique test titles by injecting properties of test case object +- 🖖 Spock like data tables with [Tagged Template Literals](#tagged-template-literal-of-rows) + +--- + +- [Demo](#demo) +- [Installation](#installation) +- [Importing](#importing) +- APIs + - [Array of Rows](#array-of-rows) + - [Usage](#usage) + - [Tagged Template Literal of rows](#tagged-template-literal-of-rows) + - [Usage](#usage-1) + +## Demo + +#### Tests without jest-each + +![Current jest tests](assets/default-demo.gif) + +#### Tests can be re-written with jest-each to: + +**`.test`** + +![Current jest tests](assets/test-demo.gif) + +**`.test` with Tagged Template Literals** + +![Current jest tests](assets/tagged-template-literal.gif) + +**`.describe`** + +![Current jest tests](assets/describe-demo.gif) + +## Installation + +`npm i --save-dev jest-each` + +`yarn add -D jest-each` + +## Importing + +jest-each is a default export so it can be imported with whatever name you like. + +```js +// es6 +import each from 'jest-each'; +``` + +```js +// es5 +const each = require('jest-each').default; +``` + +## Array of rows + +### API + +#### `each([parameters]).test(name, testFn)` + +##### `each`: + +- parameters: `Array` of Arrays with the arguments that are passed into the `testFn` for each row + - _Note_ If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. `[1, 2, 3] -> [[1], [2], [3]]` + +##### `.test`: + +- name: `String` the title of the `test`. + - Generate unique test titles by positionally injecting parameters with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): + - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). + - `%s`- String. + - `%d`- Number. + - `%i` - Integer. + - `%f` - Floating point value. + - `%j` - JSON. + - `%o` - Object. + - `%#` - Index of the test case. + - `%%` - single percent sign ('%'). This does not consume an argument. + - Or generate unique test titles by injecting properties of test case object with `$variable` + - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` + - You can use `$#` to inject the index of the test case + - You cannot use `$variable` with the `printf` formatting except for `%%` +- testFn: `Function` the test logic, this is the function that will receive the parameters of each row as function arguments + +#### `each([parameters]).describe(name, suiteFn)` + +##### `each`: + +- parameters: `Array` of Arrays with the arguments that are passed into the `suiteFn` for each row + - _Note_ If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. `[1, 2, 3] -> [[1], [2], [3]]` + +##### `.describe`: + +- name: `String` the title of the `describe` + - Generate unique test titles by positionally injecting parameters with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): + - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). + - `%s`- String. + - `%d`- Number. + - `%i` - Integer. + - `%f` - Floating point value. + - `%j` - JSON. + - `%o` - Object. + - `%#` - Index of the test case. + - `%%` - single percent sign ('%'). This does not consume an argument. + - Or generate unique test titles by injecting properties of test case object with `$variable` + - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` + - You can use `$#` to inject the index of the test case + - You cannot use `$variable` with the `printf` formatting except for `%%` +- suiteFn: `Function` the suite of `test`/`it`s to be ran, this is the function that will receive the parameters in each row as function arguments + +### Usage + +#### `.test(name, fn)` + +Alias: `.it(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test('returns the result of adding %d to %d', (a, b, expected) => { + expect(a + b).toBe(expected); +}); +``` + +```js +each([ + {a: 1, b: 1, expected: 2}, + {a: 1, b: 2, expected: 3}, + {a: 2, b: 1, expected: 3}, +]).test('returns the result of adding $a to $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); +``` + +#### `.test.only(name, fn)` + +Aliases: `.it.only(name, fn)` or `.fit(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test.only('returns the result of adding %d to %d', (a, b, expected) => { + expect(a + b).toBe(expected); +}); +``` + +#### `.test.skip(name, fn)` + +Aliases: `.it.skip(name, fn)` or `.xit(name, fn)` or `.xtest(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test.skip('returns the result of adding %d to %d', (a, b, expected) => { + expect(a + b).toBe(expected); +}); +``` + +#### `.test.concurrent(name, fn)` + +Aliases: `.it.concurrent(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test.concurrent( + 'returns the result of adding %d to %d', + (a, b, expected) => { + expect(a + b).toBe(expected); + }, +); +``` + +#### `.test.concurrent.only(name, fn)` + +Aliases: `.it.concurrent.only(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test.concurrent.only( + 'returns the result of adding %d to %d', + (a, b, expected) => { + expect(a + b).toBe(expected); + }, +); +``` + +#### `.test.concurrent.skip(name, fn)` + +Aliases: `.it.concurrent.skip(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).test.concurrent.skip( + 'returns the result of adding %d to %d', + (a, b, expected) => { + expect(a + b).toBe(expected); + }, +); +``` + +#### Asynchronous `.test(name, fn(done))` + +Alias: `.it(name, fn(done))` + +```js +each([['hello'], ['mr'], ['spy']]).test( + 'gives 007 secret message: %s', + (str, done) => { + const asynchronousSpy = message => { + expect(message).toBe(str); + done(); + }; + callSomeAsynchronousFunction(asynchronousSpy)(str); + }, +); +``` + +#### `.describe(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).describe('.add(%d, %d)', (a, b, expected) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + + test('does not mutate first arg', () => { + a + b; + expect(a).toBe(a); + }); + + test('does not mutate second arg', () => { + a + b; + expect(b).toBe(b); + }); +}); +``` + +```js +each([ + {a: 1, b: 1, expected: 2}, + {a: 1, b: 2, expected: 3}, + {a: 2, b: 1, expected: 3}, +]).describe('.add($a, $b)', ({a, b, expected}) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + + test('does not mutate first arg', () => { + a + b; + expect(a).toBe(a); + }); + + test('does not mutate second arg', () => { + a + b; + expect(b).toBe(b); + }); +}); +``` + +#### `.describe.only(name, fn)` + +Aliases: `.fdescribe(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).describe.only('.add(%d, %d)', (a, b, expected) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); +}); +``` + +#### `.describe.skip(name, fn)` + +Aliases: `.xdescribe(name, fn)` + +```js +each([ + [1, 1, 2], + [1, 2, 3], + [2, 1, 3], +]).describe.skip('.add(%d, %d)', (a, b, expected) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); +}); +``` + +--- + +## Tagged Template Literal of rows + +### API + +#### `each[tagged template].test(name, suiteFn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.test('returns $expected when adding $a to $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); +``` + +##### `each` takes a tagged template string with: + +- First row of variable name column headings separated with `|` +- One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. + +##### `.test`: + +- name: `String` the title of the `test`, use `$variable` in the name string to inject test values into the test title from the tagged template expressions + - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` + - You can use `$#` to inject the index of the table row. +- testFn: `Function` the test logic, this is the function that will receive the parameters of each row as function arguments + +#### `each[tagged template].describe(name, suiteFn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.describe('$a + $b', ({a, b, expected}) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + + test('does not mutate first arg', () => { + a + b; + expect(a).toBe(a); + }); + + test('does not mutate second arg', () => { + a + b; + expect(b).toBe(b); + }); +}); +``` + +##### `each` takes a tagged template string with: + +- First row of variable name column headings separated with `|` +- One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. + +##### `.describe`: + +- name: `String` the title of the `test`, use `$variable` in the name string to inject test values into the test title from the tagged template expressions + - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` +- suiteFn: `Function` the suite of `test`/`it`s to be ran, this is the function that will receive the parameters in each row as function arguments + +### Usage + +#### `.test(name, fn)` + +Alias: `.it(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.test('returns $expected when adding $a to $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); +``` + +#### `.test.only(name, fn)` + +Aliases: `.it.only(name, fn)` or `.fit(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.test.only('returns $expected when adding $a to $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); +``` + +#### `.test.skip(name, fn)` + +Aliases: `.it.skip(name, fn)` or `.xit(name, fn)` or `.xtest(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.test.skip('returns $expected when adding $a to $b', ({a, b, expected}) => { + expect(a + b).toBe(expected); +}); +``` + +#### Asynchronous `.test(name, fn(done))` + +Alias: `.it(name, fn(done))` + +```js +each` + str + ${'hello'} + ${'mr'} + ${'spy'} +`.test('gives 007 secret message: $str', ({str}, done) => { + const asynchronousSpy = message => { + expect(message).toBe(str); + done(); + }; + callSomeAsynchronousFunction(asynchronousSpy)(str); +}); +``` + +#### `.describe(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.describe('$a + $b', ({a, b, expected}) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); + + test('does not mutate first arg', () => { + a + b; + expect(a).toBe(a); + }); + + test('does not mutate second arg', () => { + a + b; + expect(b).toBe(b); + }); +}); +``` + +#### `.describe.only(name, fn)` + +Aliases: `.fdescribe(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.describe.only('$a + $b', ({a, b, expected}) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); +}); +``` + +#### `.describe.skip(name, fn)` + +Aliases: `.xdescribe(name, fn)` + +```js +each` + a | b | expected + ${1} | ${1} | ${2} + ${1} | ${2} | ${3} + ${2} | ${1} | ${3} +`.describe.skip('$a + $b', ({a, b, expected}) => { + test(`returns ${expected}`, () => { + expect(a + b).toBe(expected); + }); +}); +``` + +## License + +MIT diff --git a/node_modules/jest-each/build/bind.js b/node_modules/jest-each/build/bind.js new file mode 100644 index 0000000..cba0398 --- /dev/null +++ b/node_modules/jest-each/build/bind.js @@ -0,0 +1,79 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = bind; +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _array = _interopRequireDefault(require('./table/array')); +var _template = _interopRequireDefault(require('./table/template')); +var _validation = require('./validation'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +function bind(cb, supportsDone = true, needsEachError = false) { + const bindWrap = (table, ...taggedTemplateData) => { + const error = new (_jestUtil().ErrorWithStack)(undefined, bindWrap); + return function eachBind(title, test, timeout) { + title = (0, _jestUtil().convertDescriptorToString)(title); + try { + const tests = isArrayTable(taggedTemplateData) + ? buildArrayTests(title, table) + : buildTemplateTests(title, table, taggedTemplateData); + return tests.forEach(row => + needsEachError + ? cb( + row.title, + applyArguments(supportsDone, row.arguments, test), + timeout, + error + ) + : cb( + row.title, + applyArguments(supportsDone, row.arguments, test), + timeout + ) + ); + } catch (e) { + const err = new Error(e.message); + err.stack = error.stack?.replace(/^Error: /s, `Error: ${e.message}`); + return cb(title, () => { + throw err; + }); + } + }; + }; + return bindWrap; +} +const isArrayTable = data => data.length === 0; +const buildArrayTests = (title, table) => { + (0, _validation.validateArrayTable)(table); + return (0, _array.default)(title, table); +}; +const buildTemplateTests = (title, table, taggedTemplateData) => { + const headings = getHeadingKeys(table[0]); + (0, _validation.validateTemplateTableArguments)(headings, taggedTemplateData); + return (0, _template.default)(title, headings, taggedTemplateData); +}; +const getHeadingKeys = headings => + (0, _validation.extractValidTemplateHeadings)(headings) + .replace(/\s/g, '') + .split('|'); +const applyArguments = (supportsDone, params, test) => + supportsDone && params.length < test.length + ? done => test(...params, done) + : () => test(...params); diff --git a/node_modules/jest-each/build/index.d.ts b/node_modules/jest-each/build/index.d.ts new file mode 100644 index 0000000..242ccc9 --- /dev/null +++ b/node_modules/jest-each/build/index.d.ts @@ -0,0 +1,141 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Global} from '@jest/types'; + +export declare function bind( + cb: GlobalCallback, + supportsDone?: boolean, + needsEachError?: boolean, +): Global.EachTestFn; + +declare const each: { + (table: Global.EachTable, ...data: Global.TemplateData): ReturnType< + typeof install + >; + withGlobal(g: Global): ( + table: Global.EachTable, + ...data: Global.TemplateData + ) => { + describe: { + ( + title: string, + suite: Global.EachTestFn, + timeout?: number, + ): any; + skip: any; + only: any; + }; + fdescribe: any; + fit: any; + it: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): any; + skip: any; + only: any; + concurrent: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): any; + only: any; + skip: any; + }; + }; + test: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): any; + skip: any; + only: any; + concurrent: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): any; + only: any; + skip: any; + }; + }; + xdescribe: any; + xit: any; + xtest: any; + }; +}; +export default each; + +declare type GlobalCallback = ( + testName: string, + fn: Global.ConcurrentTestFn, + timeout?: number, + eachError?: Error, +) => void; + +declare const install: ( + g: Global, + table: Global.EachTable, + ...data: Global.TemplateData +) => { + describe: { + ( + title: string, + suite: Global.EachTestFn, + timeout?: number, + ): any; + skip: any; + only: any; + }; + fdescribe: any; + fit: any; + it: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): any; + skip: any; + only: any; + concurrent: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): any; + only: any; + skip: any; + }; + }; + test: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): any; + skip: any; + only: any; + concurrent: { + ( + title: string, + test: Global.EachTestFn, + timeout?: number, + ): any; + only: any; + skip: any; + }; + }; + xdescribe: any; + xit: any; + xtest: any; +}; + +export {}; diff --git a/node_modules/jest-each/build/index.js b/node_modules/jest-each/build/index.js new file mode 100644 index 0000000..bde2202 --- /dev/null +++ b/node_modules/jest-each/build/index.js @@ -0,0 +1,83 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'bind', { + enumerable: true, + get: function () { + return _bind.default; + } +}); +exports.default = void 0; +var _bind = _interopRequireDefault(require('./bind')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +const install = (g, table, ...data) => { + const bindingWithArray = data.length === 0; + const bindingWithTemplate = Array.isArray(table) && !!table.raw; + if (!bindingWithArray && !bindingWithTemplate) { + throw new Error( + '`.each` must only be called with an Array or Tagged Template Literal.' + ); + } + const test = (title, test, timeout) => + (0, _bind.default)(g.test)(table, ...data)(title, test, timeout); + test.skip = (0, _bind.default)(g.test.skip)(table, ...data); + test.only = (0, _bind.default)(g.test.only)(table, ...data); + const testConcurrent = (title, test, timeout) => + (0, _bind.default)(g.test.concurrent)(table, ...data)(title, test, timeout); + test.concurrent = testConcurrent; + testConcurrent.only = (0, _bind.default)(g.test.concurrent.only)( + table, + ...data + ); + testConcurrent.skip = (0, _bind.default)(g.test.concurrent.skip)( + table, + ...data + ); + const it = (title, test, timeout) => + (0, _bind.default)(g.it)(table, ...data)(title, test, timeout); + it.skip = (0, _bind.default)(g.it.skip)(table, ...data); + it.only = (0, _bind.default)(g.it.only)(table, ...data); + it.concurrent = testConcurrent; + const xit = (0, _bind.default)(g.xit)(table, ...data); + const fit = (0, _bind.default)(g.fit)(table, ...data); + const xtest = (0, _bind.default)(g.xtest)(table, ...data); + const describe = (title, suite, timeout) => + (0, _bind.default)(g.describe, false)(table, ...data)( + title, + suite, + timeout + ); + describe.skip = (0, _bind.default)(g.describe.skip, false)(table, ...data); + describe.only = (0, _bind.default)(g.describe.only, false)(table, ...data); + const fdescribe = (0, _bind.default)(g.fdescribe, false)(table, ...data); + const xdescribe = (0, _bind.default)(g.xdescribe, false)(table, ...data); + return { + describe, + fdescribe, + fit, + it, + test, + xdescribe, + xit, + xtest + }; +}; +const each = (table, ...data) => install(globalThis, table, ...data); +each.withGlobal = + g => + (table, ...data) => + install(g, table, ...data); +var _default = each; +exports.default = _default; diff --git a/node_modules/jest-each/build/table/array.js b/node_modules/jest-each/build/table/array.js new file mode 100644 index 0000000..cf7b91d --- /dev/null +++ b/node_modules/jest-each/build/table/array.js @@ -0,0 +1,130 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = array; +function util() { + const data = _interopRequireWildcard(require('util')); + util = function () { + return data; + }; + return data; +} +function _prettyFormat() { + const data = require('pretty-format'); + _prettyFormat = function () { + return data; + }; + return data; +} +var _interpolation = require('./interpolation'); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +const SUPPORTED_PLACEHOLDERS = /%[sdifjoOp#]/g; +const PRETTY_PLACEHOLDER = '%p'; +const INDEX_PLACEHOLDER = '%#'; +const PLACEHOLDER_PREFIX = '%'; +const ESCAPED_PLACEHOLDER_PREFIX = /%%/g; +const JEST_EACH_PLACEHOLDER_ESCAPE = '@@__JEST_EACH_PLACEHOLDER_ESCAPE__@@'; +function array(title, arrayTable) { + if (isTemplates(title, arrayTable)) { + return arrayTable.map((template, index) => ({ + arguments: [template], + title: (0, _interpolation.interpolateVariables)( + title, + template, + index + ).replace(ESCAPED_PLACEHOLDER_PREFIX, PLACEHOLDER_PREFIX) + })); + } + return normaliseTable(arrayTable).map((row, index) => ({ + arguments: row, + title: formatTitle(title, row, index) + })); +} +const isTemplates = (title, arrayTable) => + !SUPPORTED_PLACEHOLDERS.test(interpolateEscapedPlaceholders(title)) && + !isTable(arrayTable) && + arrayTable.every(col => col != null && typeof col === 'object'); +const normaliseTable = table => (isTable(table) ? table : table.map(colToRow)); +const isTable = table => table.every(Array.isArray); +const colToRow = col => [col]; +const formatTitle = (title, row, rowIndex) => + row + .reduce((formattedTitle, value) => { + const [placeholder] = getMatchingPlaceholders(formattedTitle); + const normalisedValue = normalisePlaceholderValue(value); + if (!placeholder) return formattedTitle; + if (placeholder === PRETTY_PLACEHOLDER) + return interpolatePrettyPlaceholder(formattedTitle, normalisedValue); + return util().format(formattedTitle, normalisedValue); + }, interpolateTitleIndex(interpolateEscapedPlaceholders(title), rowIndex)) + .replace(new RegExp(JEST_EACH_PLACEHOLDER_ESCAPE, 'g'), PLACEHOLDER_PREFIX); +const normalisePlaceholderValue = value => + typeof value === 'string' + ? value.replace( + new RegExp(PLACEHOLDER_PREFIX, 'g'), + JEST_EACH_PLACEHOLDER_ESCAPE + ) + : value; +const getMatchingPlaceholders = title => + title.match(SUPPORTED_PLACEHOLDERS) || []; +const interpolateEscapedPlaceholders = title => + title.replace(ESCAPED_PLACEHOLDER_PREFIX, JEST_EACH_PLACEHOLDER_ESCAPE); +const interpolateTitleIndex = (title, index) => + title.replace(INDEX_PLACEHOLDER, index.toString()); +const interpolatePrettyPlaceholder = (title, value) => + title.replace( + PRETTY_PLACEHOLDER, + (0, _prettyFormat().format)(value, { + maxDepth: 1, + min: true + }) + ); diff --git a/node_modules/jest-each/build/table/interpolation.js b/node_modules/jest-each/build/table/interpolation.js new file mode 100644 index 0000000..e7fb5c0 --- /dev/null +++ b/node_modules/jest-each/build/table/interpolation.js @@ -0,0 +1,59 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getPath = getPath; +exports.interpolateVariables = void 0; +function _jestGetType() { + const data = require('jest-get-type'); + _jestGetType = function () { + return data; + }; + return data; +} +function _prettyFormat() { + const data = require('pretty-format'); + _prettyFormat = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +const interpolateVariables = (title, template, index) => + Object.keys(template) + .reduce(getMatchingKeyPaths(title), []) // aka flatMap + .reduce(replaceKeyPathWithValue(template), title) + .replace('$#', `${index}`); +exports.interpolateVariables = interpolateVariables; +const getMatchingKeyPaths = title => (matches, key) => + matches.concat(title.match(new RegExp(`\\$${key}[\\.\\w]*`, 'g')) || []); +const replaceKeyPathWithValue = template => (title, match) => { + const keyPath = match.replace('$', '').split('.'); + const value = getPath(template, keyPath); + if ((0, _jestGetType().isPrimitive)(value)) { + return title.replace(match, String(value)); + } + return title.replace( + match, + (0, _prettyFormat().format)(value, { + maxDepth: 1, + min: true + }) + ); +}; + +/* eslint import/export: 0*/ + +function getPath(template, [head, ...tail]) { + if (!head || !Object.prototype.hasOwnProperty.call(template, head)) + return template; + return getPath(template[head], tail); +} diff --git a/node_modules/jest-each/build/table/template.js b/node_modules/jest-each/build/table/template.js new file mode 100644 index 0000000..4eb667b --- /dev/null +++ b/node_modules/jest-each/build/table/template.js @@ -0,0 +1,42 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = template; +var _interpolation = require('./interpolation'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +function template(title, headings, row) { + const table = convertRowToTable(row, headings); + const templates = convertTableToTemplates(table, headings); + return templates.map((template, index) => ({ + arguments: [template], + title: (0, _interpolation.interpolateVariables)(title, template, index) + })); +} +const convertRowToTable = (row, headings) => + Array.from({ + length: row.length / headings.length + }).map((_, index) => + row.slice( + index * headings.length, + index * headings.length + headings.length + ) + ); +const convertTableToTemplates = (table, headings) => + table.map(row => + row.reduce( + (acc, value, index) => + Object.assign(acc, { + [headings[index]]: value + }), + {} + ) + ); diff --git a/node_modules/jest-each/build/validation.js b/node_modules/jest-each/build/validation.js new file mode 100644 index 0000000..dd065e1 --- /dev/null +++ b/node_modules/jest-each/build/validation.js @@ -0,0 +1,107 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.validateTemplateTableArguments = + exports.validateArrayTable = + exports.extractValidTemplateHeadings = + void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _prettyFormat() { + const data = require('pretty-format'); + _prettyFormat = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +const EXPECTED_COLOR = _chalk().default.green; +const RECEIVED_COLOR = _chalk().default.red; +const validateArrayTable = table => { + if (!Array.isArray(table)) { + throw new Error( + '`.each` must be called with an Array or Tagged Template Literal.\n\n' + + `Instead was called with: ${(0, _prettyFormat().format)(table, { + maxDepth: 1, + min: true + })}\n` + ); + } + if (isTaggedTemplateLiteral(table)) { + if (isEmptyString(table[0])) { + throw new Error( + 'Error: `.each` called with an empty Tagged Template Literal of table data.\n' + ); + } + throw new Error( + 'Error: `.each` called with a Tagged Template Literal with no data, remember to interpolate with ${expression} syntax.\n' + ); + } + if (isEmptyTable(table)) { + throw new Error( + 'Error: `.each` called with an empty Array of table data.\n' + ); + } +}; +exports.validateArrayTable = validateArrayTable; +const isTaggedTemplateLiteral = array => array.raw !== undefined; +const isEmptyTable = table => table.length === 0; +const isEmptyString = str => typeof str === 'string' && str.trim() === ''; +const validateTemplateTableArguments = (headings, data) => { + const incompleteData = data.length % headings.length; + const missingData = headings.length - incompleteData; + if (incompleteData > 0) { + throw new Error( + `Not enough arguments supplied for given headings:\n${EXPECTED_COLOR( + headings.join(' | ') + )}\n\n` + + `Received:\n${RECEIVED_COLOR((0, _prettyFormat().format)(data))}\n\n` + + `Missing ${RECEIVED_COLOR(missingData.toString())} ${pluralize( + 'argument', + missingData + )}` + ); + } +}; +exports.validateTemplateTableArguments = validateTemplateTableArguments; +const pluralize = (word, count) => word + (count === 1 ? '' : 's'); +const START_OF_LINE = '^'; +const NEWLINE = '\\n'; +const HEADING = '\\s*[^\\s]+\\s*'; +const PIPE = '\\|'; +const REPEATABLE_HEADING = `(${PIPE}${HEADING})*`; +const HEADINGS_FORMAT = new RegExp( + START_OF_LINE + NEWLINE + HEADING + REPEATABLE_HEADING + NEWLINE, + 'g' +); +const extractValidTemplateHeadings = headings => { + const matches = headings.match(HEADINGS_FORMAT); + if (matches === null) { + throw new Error( + `Table headings do not conform to expected format:\n\n${EXPECTED_COLOR( + 'heading1 | headingN' + )}\n\nReceived:\n\n${RECEIVED_COLOR( + (0, _prettyFormat().format)(headings) + )}` + ); + } + return matches[0]; +}; +exports.extractValidTemplateHeadings = extractValidTemplateHeadings; diff --git a/node_modules/jest-each/package.json b/node_modules/jest-each/package.json new file mode 100644 index 0000000..85878d5 --- /dev/null +++ b/node_modules/jest-each/package.json @@ -0,0 +1,41 @@ +{ + "name": "jest-each", + "version": "29.2.1", + "description": "Parameterised tests for Jest", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-each" + }, + "keywords": [ + "jest", + "parameterised", + "test", + "each" + ], + "author": "Matt Phillips (mattphillips)", + "license": "MIT", + "dependencies": { + "@jest/types": "^29.2.1", + "chalk": "^4.0.0", + "jest-get-type": "^29.2.0", + "jest-util": "^29.2.1", + "pretty-format": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "4551c0fdd4d25b7206824957c7bcc6baf61e63bf" +} diff --git a/node_modules/jest-environment-node/LICENSE b/node_modules/jest-environment-node/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-environment-node/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-environment-node/build/index.d.ts b/node_modules/jest-environment-node/build/index.d.ts new file mode 100644 index 0000000..8dde21c --- /dev/null +++ b/node_modules/jest-environment-node/build/index.d.ts @@ -0,0 +1,41 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import {Context} from 'vm'; +import type {EnvironmentContext} from '@jest/environment'; +import type {Global} from '@jest/types'; +import type {JestEnvironment} from '@jest/environment'; +import type {JestEnvironmentConfig} from '@jest/environment'; +import {LegacyFakeTimers} from '@jest/fake-timers'; +import {ModernFakeTimers} from '@jest/fake-timers'; +import {ModuleMocker} from 'jest-mock'; + +declare class NodeEnvironment implements JestEnvironment { + context: Context | null; + fakeTimers: LegacyFakeTimers | null; + fakeTimersModern: ModernFakeTimers | null; + global: Global.Global; + moduleMocker: ModuleMocker | null; + customExportConditions: string[]; + constructor(config: JestEnvironmentConfig, _context: EnvironmentContext); + setup(): Promise; + teardown(): Promise; + exportConditions(): Array; + getVmContext(): Context | null; +} +export default NodeEnvironment; + +export declare const TestEnvironment: typeof NodeEnvironment; + +declare type Timer = { + id: number; + ref: () => Timer; + unref: () => Timer; +}; + +export {}; diff --git a/node_modules/jest-environment-node/build/index.js b/node_modules/jest-environment-node/build/index.js new file mode 100644 index 0000000..8c7162a --- /dev/null +++ b/node_modules/jest-environment-node/build/index.js @@ -0,0 +1,198 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = exports.TestEnvironment = void 0; +function _vm() { + const data = require('vm'); + _vm = function () { + return data; + }; + return data; +} +function _fakeTimers() { + const data = require('@jest/fake-timers'); + _fakeTimers = function () { + return data; + }; + return data; +} +function _jestMock() { + const data = require('jest-mock'); + _jestMock = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// some globals we do not want, either because deprecated or we set it ourselves +const denyList = new Set([ + 'GLOBAL', + 'root', + 'global', + 'Buffer', + 'ArrayBuffer', + 'Uint8Array', + // if env is loaded within a jest test + 'jest-symbol-do-not-touch' +]); +const nodeGlobals = new Map( + Object.getOwnPropertyNames(globalThis) + .filter(global => !denyList.has(global)) + .map(nodeGlobalsKey => { + const descriptor = Object.getOwnPropertyDescriptor( + globalThis, + nodeGlobalsKey + ); + if (!descriptor) { + throw new Error( + `No property descriptor for ${nodeGlobalsKey}, this is a bug in Jest.` + ); + } + return [nodeGlobalsKey, descriptor]; + }) +); +function isString(value) { + return typeof value === 'string'; +} +class NodeEnvironment { + context; + fakeTimers; + fakeTimersModern; + global; + moduleMocker; + customExportConditions = ['node', 'node-addons']; + + // while `context` is unused, it should always be passed + constructor(config, _context) { + const {projectConfig} = config; + this.context = (0, _vm().createContext)(); + const global = (0, _vm().runInContext)( + 'this', + Object.assign(this.context, projectConfig.testEnvironmentOptions) + ); + this.global = global; + const contextGlobals = new Set(Object.getOwnPropertyNames(global)); + for (const [nodeGlobalsKey, descriptor] of nodeGlobals) { + if (!contextGlobals.has(nodeGlobalsKey)) { + Object.defineProperty(global, nodeGlobalsKey, { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + get() { + // @ts-expect-error: no index signature + const val = globalThis[nodeGlobalsKey]; + + // override lazy getter + Object.defineProperty(global, nodeGlobalsKey, { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + value: val, + writable: + descriptor.writable === true || + // Node 19 makes performance non-readable. This is probably not the correct solution. + nodeGlobalsKey === 'performance' + }); + return val; + }, + set(val) { + // override lazy getter + Object.defineProperty(global, nodeGlobalsKey, { + configurable: descriptor.configurable, + enumerable: descriptor.enumerable, + value: val, + writable: true + }); + } + }); + } + } + + // @ts-expect-error - Buffer and gc is "missing" + global.global = global; + global.Buffer = Buffer; + global.ArrayBuffer = ArrayBuffer; + // TextEncoder (global or via 'util') references a Uint8Array constructor + // different than the global one used by users in tests. This makes sure the + // same constructor is referenced by both. + global.Uint8Array = Uint8Array; + (0, _jestUtil().installCommonGlobals)(global, projectConfig.globals); + + // Node's error-message stack size is limited at 10, but it's pretty useful + // to see more than that when a test fails. + global.Error.stackTraceLimit = 100; + if ('customExportConditions' in projectConfig.testEnvironmentOptions) { + const {customExportConditions} = projectConfig.testEnvironmentOptions; + if ( + Array.isArray(customExportConditions) && + customExportConditions.every(isString) + ) { + this.customExportConditions = customExportConditions; + } else { + throw new Error( + 'Custom export conditions specified but they are not an array of strings' + ); + } + } + this.moduleMocker = new (_jestMock().ModuleMocker)(global); + const timerIdToRef = id => ({ + id, + ref() { + return this; + }, + unref() { + return this; + } + }); + const timerRefToId = timer => timer?.id; + this.fakeTimers = new (_fakeTimers().LegacyFakeTimers)({ + config: projectConfig, + global, + moduleMocker: this.moduleMocker, + timerConfig: { + idToRef: timerIdToRef, + refToId: timerRefToId + } + }); + this.fakeTimersModern = new (_fakeTimers().ModernFakeTimers)({ + config: projectConfig, + global + }); + } + + // eslint-disable-next-line @typescript-eslint/no-empty-function + async setup() {} + async teardown() { + if (this.fakeTimers) { + this.fakeTimers.dispose(); + } + if (this.fakeTimersModern) { + this.fakeTimersModern.dispose(); + } + this.context = null; + this.fakeTimers = null; + this.fakeTimersModern = null; + } + exportConditions() { + return this.customExportConditions; + } + getVmContext() { + return this.context; + } +} +exports.default = NodeEnvironment; +const TestEnvironment = NodeEnvironment; +exports.TestEnvironment = TestEnvironment; diff --git a/node_modules/jest-environment-node/package.json b/node_modules/jest-environment-node/package.json new file mode 100644 index 0000000..34c86b2 --- /dev/null +++ b/node_modules/jest-environment-node/package.json @@ -0,0 +1,37 @@ +{ + "name": "jest-environment-node", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-environment-node" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/environment": "^29.2.2", + "@jest/fake-timers": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/node": "*", + "jest-mock": "^29.2.2", + "jest-util": "^29.2.1" + }, + "devDependencies": { + "@jest/test-utils": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-get-type/LICENSE b/node_modules/jest-get-type/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-get-type/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-get-type/build/index.d.ts b/node_modules/jest-get-type/build/index.d.ts new file mode 100644 index 0000000..096d2d1 --- /dev/null +++ b/node_modules/jest-get-type/build/index.d.ts @@ -0,0 +1,27 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare function getType(value: unknown): ValueType; + +export declare const isPrimitive: (value: unknown) => boolean; + +declare type ValueType = + | 'array' + | 'bigint' + | 'boolean' + | 'function' + | 'null' + | 'number' + | 'object' + | 'regexp' + | 'map' + | 'set' + | 'date' + | 'string' + | 'symbol' + | 'undefined'; + +export {}; diff --git a/node_modules/jest-get-type/build/index.js b/node_modules/jest-get-type/build/index.js new file mode 100644 index 0000000..b8fb922 --- /dev/null +++ b/node_modules/jest-get-type/build/index.js @@ -0,0 +1,53 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getType = getType; +exports.isPrimitive = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// get the type of a value with handling the edge cases like `typeof []` +// and `typeof null` +function getType(value) { + if (value === undefined) { + return 'undefined'; + } else if (value === null) { + return 'null'; + } else if (Array.isArray(value)) { + return 'array'; + } else if (typeof value === 'boolean') { + return 'boolean'; + } else if (typeof value === 'function') { + return 'function'; + } else if (typeof value === 'number') { + return 'number'; + } else if (typeof value === 'string') { + return 'string'; + } else if (typeof value === 'bigint') { + return 'bigint'; + } else if (typeof value === 'object') { + if (value != null) { + if (value.constructor === RegExp) { + return 'regexp'; + } else if (value.constructor === Map) { + return 'map'; + } else if (value.constructor === Set) { + return 'set'; + } else if (value.constructor === Date) { + return 'date'; + } + } + return 'object'; + } else if (typeof value === 'symbol') { + return 'symbol'; + } + throw new Error(`value of unknown type: ${value}`); +} +const isPrimitive = value => Object(value) !== value; +exports.isPrimitive = isPrimitive; diff --git a/node_modules/jest-get-type/package.json b/node_modules/jest-get-type/package.json new file mode 100644 index 0000000..2443eab --- /dev/null +++ b/node_modules/jest-get-type/package.json @@ -0,0 +1,27 @@ +{ + "name": "jest-get-type", + "description": "A utility function to get the type of a value", + "version": "29.2.0", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-get-type" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "ee5b37a4f4433afcfffb0356cea47739d8092287" +} diff --git a/node_modules/jest-haste-map/LICENSE b/node_modules/jest-haste-map/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-haste-map/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-haste-map/build/HasteFS.js b/node_modules/jest-haste-map/build/HasteFS.js new file mode 100644 index 0000000..0135483 --- /dev/null +++ b/node_modules/jest-haste-map/build/HasteFS.js @@ -0,0 +1,139 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _constants = _interopRequireDefault(require('./constants')); +var fastPath = _interopRequireWildcard(require('./lib/fast_path')); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class HasteFS { + _rootDir; + _files; + constructor({rootDir, files}) { + this._rootDir = rootDir; + this._files = files; + } + getModuleName(file) { + const fileMetadata = this._getFileData(file); + return (fileMetadata && fileMetadata[_constants.default.ID]) || null; + } + getSize(file) { + const fileMetadata = this._getFileData(file); + return (fileMetadata && fileMetadata[_constants.default.SIZE]) || null; + } + getDependencies(file) { + const fileMetadata = this._getFileData(file); + if (fileMetadata) { + return fileMetadata[_constants.default.DEPENDENCIES] + ? fileMetadata[_constants.default.DEPENDENCIES].split( + _constants.default.DEPENDENCY_DELIM + ) + : []; + } else { + return null; + } + } + getSha1(file) { + const fileMetadata = this._getFileData(file); + return (fileMetadata && fileMetadata[_constants.default.SHA1]) || null; + } + exists(file) { + return this._getFileData(file) != null; + } + getAllFiles() { + return Array.from(this.getAbsoluteFileIterator()); + } + getFileIterator() { + return this._files.keys(); + } + *getAbsoluteFileIterator() { + for (const file of this.getFileIterator()) { + yield fastPath.resolve(this._rootDir, file); + } + } + matchFiles(pattern) { + if (!(pattern instanceof RegExp)) { + pattern = new RegExp(pattern); + } + const files = []; + for (const file of this.getAbsoluteFileIterator()) { + if (pattern.test(file)) { + files.push(file); + } + } + return files; + } + matchFilesWithGlob(globs, root) { + const files = new Set(); + const matcher = (0, _jestUtil().globsToMatcher)(globs); + for (const file of this.getAbsoluteFileIterator()) { + const filePath = root ? fastPath.relative(root, file) : file; + if (matcher((0, _jestUtil().replacePathSepForGlob)(filePath))) { + files.add(file); + } + } + return files; + } + _getFileData(file) { + const relativePath = fastPath.relative(this._rootDir, file); + return this._files.get(relativePath); + } +} +exports.default = HasteFS; diff --git a/node_modules/jest-haste-map/build/ModuleMap.js b/node_modules/jest-haste-map/build/ModuleMap.js new file mode 100644 index 0000000..207878b --- /dev/null +++ b/node_modules/jest-haste-map/build/ModuleMap.js @@ -0,0 +1,249 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _constants = _interopRequireDefault(require('./constants')); +var fastPath = _interopRequireWildcard(require('./lib/fast_path')); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const EMPTY_OBJ = {}; +const EMPTY_MAP = new Map(); +class ModuleMap { + static DuplicateHasteCandidatesError; + _raw; + json; + static mapToArrayRecursive(map) { + let arr = Array.from(map); + if (arr[0] && arr[0][1] instanceof Map) { + arr = arr.map(el => [el[0], this.mapToArrayRecursive(el[1])]); + } + return arr; + } + static mapFromArrayRecursive(arr) { + if (arr[0] && Array.isArray(arr[1])) { + arr = arr.map(el => [el[0], this.mapFromArrayRecursive(el[1])]); + } + return new Map(arr); + } + constructor(raw) { + this._raw = raw; + } + getModule(name, platform, supportsNativePlatform, type) { + if (type == null) { + type = _constants.default.MODULE; + } + const module = this._getModuleMetadata( + name, + platform, + !!supportsNativePlatform + ); + if (module && module[_constants.default.TYPE] === type) { + const modulePath = module[_constants.default.PATH]; + return modulePath && fastPath.resolve(this._raw.rootDir, modulePath); + } + return null; + } + getPackage(name, platform, _supportsNativePlatform) { + return this.getModule(name, platform, null, _constants.default.PACKAGE); + } + getMockModule(name) { + const mockPath = + this._raw.mocks.get(name) || this._raw.mocks.get(`${name}/index`); + return mockPath && fastPath.resolve(this._raw.rootDir, mockPath); + } + getRawModuleMap() { + return { + duplicates: this._raw.duplicates, + map: this._raw.map, + mocks: this._raw.mocks, + rootDir: this._raw.rootDir + }; + } + toJSON() { + if (!this.json) { + this.json = { + duplicates: ModuleMap.mapToArrayRecursive(this._raw.duplicates), + map: Array.from(this._raw.map), + mocks: Array.from(this._raw.mocks), + rootDir: this._raw.rootDir + }; + } + return this.json; + } + static fromJSON(serializableModuleMap) { + return new ModuleMap({ + duplicates: ModuleMap.mapFromArrayRecursive( + serializableModuleMap.duplicates + ), + map: new Map(serializableModuleMap.map), + mocks: new Map(serializableModuleMap.mocks), + rootDir: serializableModuleMap.rootDir + }); + } + + /** + * When looking up a module's data, we walk through each eligible platform for + * the query. For each platform, we want to check if there are known + * duplicates for that name+platform pair. The duplication logic normally + * removes elements from the `map` object, but we want to check upfront to be + * extra sure. If metadata exists both in the `duplicates` object and the + * `map`, this would be a bug. + */ + _getModuleMetadata(name, platform, supportsNativePlatform) { + const map = this._raw.map.get(name) || EMPTY_OBJ; + const dupMap = this._raw.duplicates.get(name) || EMPTY_MAP; + if (platform != null) { + this._assertNoDuplicates( + name, + platform, + supportsNativePlatform, + dupMap.get(platform) + ); + if (map[platform] != null) { + return map[platform]; + } + } + if (supportsNativePlatform) { + this._assertNoDuplicates( + name, + _constants.default.NATIVE_PLATFORM, + supportsNativePlatform, + dupMap.get(_constants.default.NATIVE_PLATFORM) + ); + if (map[_constants.default.NATIVE_PLATFORM]) { + return map[_constants.default.NATIVE_PLATFORM]; + } + } + this._assertNoDuplicates( + name, + _constants.default.GENERIC_PLATFORM, + supportsNativePlatform, + dupMap.get(_constants.default.GENERIC_PLATFORM) + ); + if (map[_constants.default.GENERIC_PLATFORM]) { + return map[_constants.default.GENERIC_PLATFORM]; + } + return null; + } + _assertNoDuplicates(name, platform, supportsNativePlatform, relativePathSet) { + if (relativePathSet == null) { + return; + } + // Force flow refinement + const previousSet = relativePathSet; + const duplicates = new Map(); + for (const [relativePath, type] of previousSet) { + const duplicatePath = fastPath.resolve(this._raw.rootDir, relativePath); + duplicates.set(duplicatePath, type); + } + throw new DuplicateHasteCandidatesError( + name, + platform, + supportsNativePlatform, + duplicates + ); + } + static create(rootDir) { + return new ModuleMap({ + duplicates: new Map(), + map: new Map(), + mocks: new Map(), + rootDir + }); + } +} +exports.default = ModuleMap; +class DuplicateHasteCandidatesError extends Error { + hasteName; + platform; + supportsNativePlatform; + duplicatesSet; + constructor(name, platform, supportsNativePlatform, duplicatesSet) { + const platformMessage = getPlatformMessage(platform); + super( + `The name \`${name}\` was looked up in the Haste module map. It ` + + 'cannot be resolved, because there exists several different ' + + 'files, or packages, that provide a module for ' + + `that particular name and platform. ${platformMessage} You must ` + + `delete or exclude files until there remains only one of these:\n\n${Array.from( + duplicatesSet + ) + .map( + ([dupFilePath, dupFileType]) => + ` * \`${dupFilePath}\` (${getTypeMessage(dupFileType)})\n` + ) + .sort() + .join('')}` + ); + this.hasteName = name; + this.platform = platform; + this.supportsNativePlatform = supportsNativePlatform; + this.duplicatesSet = duplicatesSet; + } +} +function getPlatformMessage(platform) { + if (platform === _constants.default.GENERIC_PLATFORM) { + return 'The platform is generic (no extension).'; + } + return `The platform extension is \`${platform}\`.`; +} +function getTypeMessage(type) { + switch (type) { + case _constants.default.MODULE: + return 'module'; + case _constants.default.PACKAGE: + return 'package'; + } + return 'unknown'; +} +ModuleMap.DuplicateHasteCandidatesError = DuplicateHasteCandidatesError; diff --git a/node_modules/jest-haste-map/build/blacklist.js b/node_modules/jest-haste-map/build/blacklist.js new file mode 100644 index 0000000..3595fca --- /dev/null +++ b/node_modules/jest-haste-map/build/blacklist.js @@ -0,0 +1,64 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// This list is compiled after the MDN list of the most common MIME types (see +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/ +// Complete_list_of_MIME_types). +// +// Only MIME types starting with "image/", "video/", "audio/" and "font/" are +// reflected in the list. Adding "application/" is too risky since some text +// file formats (like ".js" and ".json") have an "application/" MIME type. +// +// Feel free to add any extensions that cannot be a Haste module. + +const extensions = new Set([ + // JSONs are never haste modules, except for "package.json", which is handled. + '.json', + // Image extensions. + '.bmp', + '.gif', + '.ico', + '.jpeg', + '.jpg', + '.png', + '.svg', + '.tiff', + '.tif', + '.webp', + // Video extensions. + '.avi', + '.mp4', + '.mpeg', + '.mpg', + '.ogv', + '.webm', + '.3gp', + '.3g2', + // Audio extensions. + '.aac', + '.midi', + '.mid', + '.mp3', + '.oga', + '.wav', + '.3gp', + '.3g2', + // Font extensions. + '.eot', + '.otf', + '.ttf', + '.woff', + '.woff2' +]); +var _default = extensions; +exports.default = _default; diff --git a/node_modules/jest-haste-map/build/constants.js b/node_modules/jest-haste-map/build/constants.js new file mode 100644 index 0000000..7fdbc96 --- /dev/null +++ b/node_modules/jest-haste-map/build/constants.js @@ -0,0 +1,46 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* + * This file exports a set of constants that are used for Jest's haste map + * serialization. On very large repositories, the haste map cache becomes very + * large to the point where it is the largest overhead in starting up Jest. + * + * This constant key map allows to keep the map smaller without having to build + * a custom serialization library. + */ + +/* eslint-disable sort-keys */ +const constants = { + /* dependency serialization */ + DEPENDENCY_DELIM: '\0', + /* file map attributes */ + ID: 0, + MTIME: 1, + SIZE: 2, + VISITED: 3, + DEPENDENCIES: 4, + SHA1: 5, + /* module map attributes */ + PATH: 0, + TYPE: 1, + /* module types */ + MODULE: 0, + PACKAGE: 1, + /* platforms */ + GENERIC_PLATFORM: 'g', + NATIVE_PLATFORM: 'native' +}; +/* eslint-enable */ +var _default = constants; +exports.default = _default; diff --git a/node_modules/jest-haste-map/build/crawlers/node.js b/node_modules/jest-haste-map/build/crawlers/node.js new file mode 100644 index 0000000..3ef6ee2 --- /dev/null +++ b/node_modules/jest-haste-map/build/crawlers/node.js @@ -0,0 +1,269 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.nodeCrawl = nodeCrawl; +function _child_process() { + const data = require('child_process'); + _child_process = function () { + return data; + }; + return data; +} +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +var _constants = _interopRequireDefault(require('../constants')); +var fastPath = _interopRequireWildcard(require('../lib/fast_path')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +async function hasNativeFindSupport(forceNodeFilesystemAPI) { + if (forceNodeFilesystemAPI) { + return false; + } + try { + return await new Promise(resolve => { + // Check the find binary supports the non-POSIX -iname parameter wrapped in parens. + const args = [ + '.', + '-type', + 'f', + '(', + '-iname', + '*.ts', + '-o', + '-iname', + '*.js', + ')' + ]; + const child = (0, _child_process().spawn)('find', args, { + cwd: __dirname + }); + child.on('error', () => { + resolve(false); + }); + child.on('exit', code => { + resolve(code === 0); + }); + }); + } catch { + return false; + } +} +function find(roots, extensions, ignore, enableSymlinks, callback) { + const result = []; + let activeCalls = 0; + function search(directory) { + activeCalls++; + fs().readdir( + directory, + { + withFileTypes: true + }, + (err, entries) => { + activeCalls--; + if (err) { + if (activeCalls === 0) { + callback(result); + } + return; + } + entries.forEach(entry => { + const file = path().join(directory, entry.name); + if (ignore(file)) { + return; + } + if (entry.isSymbolicLink()) { + return; + } + if (entry.isDirectory()) { + search(file); + return; + } + activeCalls++; + const stat = enableSymlinks ? fs().stat : fs().lstat; + stat(file, (err, stat) => { + activeCalls--; + + // This logic is unnecessary for node > v10.10, but leaving it in + // since we need it for backwards-compatibility still. + if (!err && stat && !stat.isSymbolicLink()) { + if (stat.isDirectory()) { + search(file); + } else { + const ext = path().extname(file).substr(1); + if (extensions.indexOf(ext) !== -1) { + result.push([file, stat.mtime.getTime(), stat.size]); + } + } + } + if (activeCalls === 0) { + callback(result); + } + }); + }); + if (activeCalls === 0) { + callback(result); + } + } + ); + } + if (roots.length > 0) { + roots.forEach(search); + } else { + callback(result); + } +} +function findNative(roots, extensions, ignore, enableSymlinks, callback) { + const args = Array.from(roots); + if (enableSymlinks) { + args.push('(', '-type', 'f', '-o', '-type', 'l', ')'); + } else { + args.push('-type', 'f'); + } + if (extensions.length) { + args.push('('); + } + extensions.forEach((ext, index) => { + if (index) { + args.push('-o'); + } + args.push('-iname'); + args.push(`*.${ext}`); + }); + if (extensions.length) { + args.push(')'); + } + const child = (0, _child_process().spawn)('find', args); + let stdout = ''; + if (child.stdout === null) { + throw new Error( + 'stdout is null - this should never happen. Please open up an issue at https://github.com/facebook/jest' + ); + } + child.stdout.setEncoding('utf-8'); + child.stdout.on('data', data => (stdout += data)); + child.stdout.on('close', () => { + const lines = stdout + .trim() + .split('\n') + .filter(x => !ignore(x)); + const result = []; + let count = lines.length; + if (!count) { + callback([]); + } else { + lines.forEach(path => { + fs().stat(path, (err, stat) => { + // Filter out symlinks that describe directories + if (!err && stat && !stat.isDirectory()) { + result.push([path, stat.mtime.getTime(), stat.size]); + } + if (--count === 0) { + callback(result); + } + }); + }); + } + }); +} +async function nodeCrawl(options) { + const { + data, + extensions, + forceNodeFilesystemAPI, + ignore, + rootDir, + enableSymlinks, + roots + } = options; + const useNativeFind = await hasNativeFindSupport(forceNodeFilesystemAPI); + return new Promise(resolve => { + const callback = list => { + const files = new Map(); + const removedFiles = new Map(data.files); + list.forEach(fileData => { + const [filePath, mtime, size] = fileData; + const relativeFilePath = fastPath.relative(rootDir, filePath); + const existingFile = data.files.get(relativeFilePath); + if (existingFile && existingFile[_constants.default.MTIME] === mtime) { + files.set(relativeFilePath, existingFile); + } else { + // See ../constants.js; SHA-1 will always be null and fulfilled later. + files.set(relativeFilePath, ['', mtime, size, 0, '', null]); + } + removedFiles.delete(relativeFilePath); + }); + data.files = files; + resolve({ + hasteMap: data, + removedFiles + }); + }; + if (useNativeFind) { + findNative(roots, extensions, ignore, enableSymlinks, callback); + } else { + find(roots, extensions, ignore, enableSymlinks, callback); + } + }); +} diff --git a/node_modules/jest-haste-map/build/crawlers/watchman.js b/node_modules/jest-haste-map/build/crawlers/watchman.js new file mode 100644 index 0000000..c69b4ca --- /dev/null +++ b/node_modules/jest-haste-map/build/crawlers/watchman.js @@ -0,0 +1,339 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.watchmanCrawl = watchmanCrawl; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _fbWatchman() { + const data = _interopRequireDefault(require('fb-watchman')); + _fbWatchman = function () { + return data; + }; + return data; +} +var _constants = _interopRequireDefault(require('../constants')); +var fastPath = _interopRequireWildcard(require('../lib/fast_path')); +var _normalizePathSep = _interopRequireDefault( + require('../lib/normalizePathSep') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const watchmanURL = 'https://facebook.github.io/watchman/docs/troubleshooting'; +function WatchmanError(error) { + error.message = + `Watchman error: ${error.message.trim()}. Make sure watchman ` + + `is running for this project. See ${watchmanURL}.`; + return error; +} + +/** + * Wrap watchman capabilityCheck method as a promise. + * + * @param client watchman client + * @param caps capabilities to verify + * @returns a promise resolving to a list of verified capabilities + */ +async function capabilityCheck(client, caps) { + return new Promise((resolve, reject) => { + client.capabilityCheck( + // @ts-expect-error: incorrectly typed + caps, + (error, response) => { + if (error) { + reject(error); + } else { + resolve(response); + } + } + ); + }); +} +async function watchmanCrawl(options) { + const fields = ['name', 'exists', 'mtime_ms', 'size']; + const {data, extensions, ignore, rootDir, roots} = options; + const defaultWatchExpression = ['allof', ['type', 'f']]; + const clocks = data.clocks; + const client = new (_fbWatchman().default.Client)(); + + // https://facebook.github.io/watchman/docs/capabilities.html + // Check adds about ~28ms + const capabilities = await capabilityCheck(client, { + // If a required capability is missing then an error will be thrown, + // we don't need this assertion, so using optional instead. + optional: ['suffix-set'] + }); + if (capabilities?.capabilities['suffix-set']) { + // If available, use the optimized `suffix-set` operation: + // https://facebook.github.io/watchman/docs/expr/suffix.html#suffix-set + defaultWatchExpression.push(['suffix', extensions]); + } else { + // Otherwise use the older and less optimal suffix tuple array + defaultWatchExpression.push([ + 'anyof', + ...extensions.map(extension => ['suffix', extension]) + ]); + } + let clientError; + client.on('error', error => (clientError = WatchmanError(error))); + const cmd = (...args) => + new Promise((resolve, reject) => + client.command(args, (error, result) => + error ? reject(WatchmanError(error)) : resolve(result) + ) + ); + if (options.computeSha1) { + const {capabilities} = await cmd('list-capabilities'); + if (capabilities.indexOf('field-content.sha1hex') !== -1) { + fields.push('content.sha1hex'); + } + } + async function getWatchmanRoots(roots) { + const watchmanRoots = new Map(); + await Promise.all( + roots.map(async root => { + const response = await cmd('watch-project', root); + const existing = watchmanRoots.get(response.watch); + // A root can only be filtered if it was never seen with a + // relative_path before. + const canBeFiltered = !existing || existing.length > 0; + if (canBeFiltered) { + if (response.relative_path) { + watchmanRoots.set( + response.watch, + (existing || []).concat(response.relative_path) + ); + } else { + // Make the filter directories an empty array to signal that this + // root was already seen and needs to be watched for all files or + // directories. + watchmanRoots.set(response.watch, []); + } + } + }) + ); + return watchmanRoots; + } + async function queryWatchmanForDirs(rootProjectDirMappings) { + const results = new Map(); + let isFresh = false; + await Promise.all( + Array.from(rootProjectDirMappings).map( + async ([root, directoryFilters]) => { + const expression = Array.from(defaultWatchExpression); + const glob = []; + if (directoryFilters.length > 0) { + expression.push([ + 'anyof', + ...directoryFilters.map(dir => ['dirname', dir]) + ]); + for (const directory of directoryFilters) { + for (const extension of extensions) { + glob.push(`${directory}/**/*.${extension}`); + } + } + } else { + for (const extension of extensions) { + glob.push(`**/*.${extension}`); + } + } + + // Jest is only going to store one type of clock; a string that + // represents a local clock. However, the Watchman crawler supports + // a second type of clock that can be written by automation outside of + // Jest, called an "scm query", which fetches changed files based on + // source control mergebases. The reason this is necessary is because + // local clocks are not portable across systems, but scm queries are. + // By using scm queries, we can create the haste map on a different + // system and import it, transforming the clock into a local clock. + const since = clocks.get(fastPath.relative(rootDir, root)); + const query = + since !== undefined + ? // Use the `since` generator if we have a clock available + { + expression, + fields, + since + } + : // Otherwise use the `glob` filter + { + expression, + fields, + glob, + glob_includedotfiles: true + }; + const response = await cmd('query', root, query); + if ('warning' in response) { + console.warn('watchman warning: ', response.warning); + } + + // When a source-control query is used, we ignore the "is fresh" + // response from Watchman because it will be true despite the query + // being incremental. + const isSourceControlQuery = + typeof since !== 'string' && + since?.scm?.['mergebase-with'] !== undefined; + if (!isSourceControlQuery) { + isFresh = isFresh || response.is_fresh_instance; + } + results.set(root, response); + } + ) + ); + return { + isFresh, + results + }; + } + let files = data.files; + let removedFiles = new Map(); + const changedFiles = new Map(); + let results; + let isFresh = false; + try { + const watchmanRoots = await getWatchmanRoots(roots); + const watchmanFileResults = await queryWatchmanForDirs(watchmanRoots); + + // Reset the file map if watchman was restarted and sends us a list of + // files. + if (watchmanFileResults.isFresh) { + files = new Map(); + removedFiles = new Map(data.files); + isFresh = true; + } + results = watchmanFileResults.results; + } finally { + client.end(); + } + if (clientError) { + throw clientError; + } + for (const [watchRoot, response] of results) { + const fsRoot = (0, _normalizePathSep.default)(watchRoot); + const relativeFsRoot = fastPath.relative(rootDir, fsRoot); + clocks.set( + relativeFsRoot, + // Ensure we persist only the local clock. + typeof response.clock === 'string' ? response.clock : response.clock.clock + ); + for (const fileData of response.files) { + const filePath = + fsRoot + path().sep + (0, _normalizePathSep.default)(fileData.name); + const relativeFilePath = fastPath.relative(rootDir, filePath); + const existingFileData = data.files.get(relativeFilePath); + + // If watchman is fresh, the removed files map starts with all files + // and we remove them as we verify they still exist. + if (isFresh && existingFileData && fileData.exists) { + removedFiles.delete(relativeFilePath); + } + if (!fileData.exists) { + // No need to act on files that do not exist and were not tracked. + if (existingFileData) { + files.delete(relativeFilePath); + + // If watchman is not fresh, we will know what specific files were + // deleted since we last ran and can track only those files. + if (!isFresh) { + removedFiles.set(relativeFilePath, existingFileData); + } + } + } else if (!ignore(filePath)) { + const mtime = + typeof fileData.mtime_ms === 'number' + ? fileData.mtime_ms + : fileData.mtime_ms.toNumber(); + const size = fileData.size; + let sha1hex = fileData['content.sha1hex']; + if (typeof sha1hex !== 'string' || sha1hex.length !== 40) { + sha1hex = undefined; + } + let nextData; + if ( + existingFileData && + existingFileData[_constants.default.MTIME] === mtime + ) { + nextData = existingFileData; + } else if ( + existingFileData && + sha1hex && + existingFileData[_constants.default.SHA1] === sha1hex + ) { + nextData = [ + existingFileData[0], + mtime, + existingFileData[2], + existingFileData[3], + existingFileData[4], + existingFileData[5] + ]; + } else { + // See ../constants.ts + nextData = ['', mtime, size, 0, '', sha1hex ?? null]; + } + files.set(relativeFilePath, nextData); + changedFiles.set(relativeFilePath, nextData); + } + } + } + data.files = files; + return { + changedFiles: isFresh ? undefined : changedFiles, + hasteMap: data, + removedFiles + }; +} diff --git a/node_modules/jest-haste-map/build/getMockName.js b/node_modules/jest-haste-map/build/getMockName.js new file mode 100644 index 0000000..328763d --- /dev/null +++ b/node_modules/jest-haste-map/build/getMockName.js @@ -0,0 +1,69 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const MOCKS_PATTERN = `${path().sep}__mocks__${path().sep}`; +const getMockName = filePath => { + const mockPath = filePath.split(MOCKS_PATTERN)[1]; + return mockPath + .substring(0, mockPath.lastIndexOf(path().extname(mockPath))) + .replace(/\\/g, '/'); +}; +var _default = getMockName; +exports.default = _default; diff --git a/node_modules/jest-haste-map/build/index.d.ts b/node_modules/jest-haste-map/build/index.d.ts new file mode 100644 index 0000000..c30e5de --- /dev/null +++ b/node_modules/jest-haste-map/build/index.d.ts @@ -0,0 +1,241 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import type {Config} from '@jest/types'; +import type {Stats} from 'graceful-fs'; + +declare type ChangeEvent = { + eventsQueue: EventsQueue; + hasteFS: HasteFS; + moduleMap: ModuleMap_2; +}; + +export declare class DuplicateError extends Error { + mockPath1: string; + mockPath2: string; + constructor(mockPath1: string, mockPath2: string); +} + +declare class DuplicateHasteCandidatesError extends Error { + hasteName: string; + platform: string | null; + supportsNativePlatform: boolean; + duplicatesSet: DuplicatesSet; + constructor( + name: string, + platform: string, + supportsNativePlatform: boolean, + duplicatesSet: DuplicatesSet, + ); +} + +declare type DuplicatesIndex = Map>; + +declare type DuplicatesSet = Map; + +declare type EventsQueue = Array<{ + filePath: string; + stat: Stats | undefined; + type: string; +}>; + +declare type FileData = Map; + +declare type FileMetaData = [ + id: string, + mtime: number, + size: number, + visited: 0 | 1, + dependencies: string, + sha1: string | null | undefined, +]; + +declare class HasteFS implements IHasteFS { + private readonly _rootDir; + private readonly _files; + constructor({rootDir, files}: {rootDir: string; files: FileData}); + getModuleName(file: string): string | null; + getSize(file: string): number | null; + getDependencies(file: string): Array | null; + getSha1(file: string): string | null; + exists(file: string): boolean; + getAllFiles(): Array; + getFileIterator(): Iterable; + getAbsoluteFileIterator(): Iterable; + matchFiles(pattern: RegExp | string): Array; + matchFilesWithGlob(globs: Array, root: string | null): Set; + private _getFileData; +} + +declare type HasteMapStatic = { + getCacheFilePath( + tmpdir: string, + name: string, + ...extra: Array + ): string; + getModuleMapFromJSON(json: S): IModuleMap; +}; + +declare type HasteRegExp = RegExp | ((str: string) => boolean); + +declare type HType = { + ID: 0; + MTIME: 1; + SIZE: 2; + VISITED: 3; + DEPENDENCIES: 4; + SHA1: 5; + PATH: 0; + TYPE: 1; + MODULE: 0; + PACKAGE: 1; + GENERIC_PLATFORM: 'g'; + NATIVE_PLATFORM: 'native'; + DEPENDENCY_DELIM: '\0'; +}; + +declare type HTypeValue = HType[keyof HType]; + +export declare interface IHasteFS { + exists(path: string): boolean; + getAbsoluteFileIterator(): Iterable; + getAllFiles(): Array; + getDependencies(file: string): Array | null; + getSize(path: string): number | null; + matchFiles(pattern: RegExp | string): Array; + matchFilesWithGlob( + globs: ReadonlyArray, + root: string | null, + ): Set; +} + +export declare interface IHasteMap { + on(eventType: 'change', handler: (event: ChangeEvent) => void): void; + build(): Promise<{ + hasteFS: IHasteFS; + moduleMap: IModuleMap; + }>; +} + +declare type IJestHasteMap = HasteMapStatic & { + create(options: Options): Promise; + getStatic(config: Config.ProjectConfig): HasteMapStatic; +}; + +export declare interface IModuleMap { + getModule( + name: string, + platform?: string | null, + supportsNativePlatform?: boolean | null, + type?: HTypeValue | null, + ): string | null; + getPackage( + name: string, + platform: string | null | undefined, + _supportsNativePlatform: boolean | null, + ): string | null; + getMockModule(name: string): string | undefined; + getRawModuleMap(): RawModuleMap; + toJSON(): S; +} + +declare const JestHasteMap: IJestHasteMap; +export default JestHasteMap; + +declare type MockData = Map; + +export declare const ModuleMap: { + create: (rootPath: string) => IModuleMap; +}; + +declare class ModuleMap_2 implements IModuleMap { + static DuplicateHasteCandidatesError: typeof DuplicateHasteCandidatesError; + private readonly _raw; + private json; + private static mapToArrayRecursive; + private static mapFromArrayRecursive; + constructor(raw: RawModuleMap); + getModule( + name: string, + platform?: string | null, + supportsNativePlatform?: boolean | null, + type?: HTypeValue | null, + ): string | null; + getPackage( + name: string, + platform: string | null | undefined, + _supportsNativePlatform: boolean | null, + ): string | null; + getMockModule(name: string): string | undefined; + getRawModuleMap(): RawModuleMap; + toJSON(): SerializableModuleMap; + static fromJSON(serializableModuleMap: SerializableModuleMap): ModuleMap_2; + /** + * When looking up a module's data, we walk through each eligible platform for + * the query. For each platform, we want to check if there are known + * duplicates for that name+platform pair. The duplication logic normally + * removes elements from the `map` object, but we want to check upfront to be + * extra sure. If metadata exists both in the `duplicates` object and the + * `map`, this would be a bug. + */ + private _getModuleMetadata; + private _assertNoDuplicates; + static create(rootDir: string): ModuleMap_2; +} + +declare type ModuleMapData = Map; + +declare type ModuleMapItem = { + [platform: string]: ModuleMetaData; +}; + +declare type ModuleMetaData = [path: string, type: number]; + +declare type Options = { + cacheDirectory?: string; + computeDependencies?: boolean; + computeSha1?: boolean; + console?: Console; + dependencyExtractor?: string | null; + enableSymlinks?: boolean; + extensions: Array; + forceNodeFilesystemAPI?: boolean; + hasteImplModulePath?: string; + hasteMapModulePath?: string; + id: string; + ignorePattern?: HasteRegExp; + maxWorkers: number; + mocksPattern?: string; + platforms: Array; + resetCache?: boolean; + retainAllFiles: boolean; + rootDir: string; + roots: Array; + skipPackageJson?: boolean; + throwOnModuleCollision?: boolean; + useWatchman?: boolean; + watch?: boolean; +}; + +declare type RawModuleMap = { + rootDir: string; + duplicates: DuplicatesIndex; + map: ModuleMapData; + mocks: MockData; +}; + +export declare type SerializableModuleMap = { + duplicates: ReadonlyArray<[string, [string, [string, [string, number]]]]>; + map: ReadonlyArray<[string, ValueType]>; + mocks: ReadonlyArray<[string, ValueType]>; + rootDir: string; +}; + +declare type ValueType = T extends Map ? V : never; + +export {}; diff --git a/node_modules/jest-haste-map/build/index.js b/node_modules/jest-haste-map/build/index.js new file mode 100644 index 0000000..ea9e57c --- /dev/null +++ b/node_modules/jest-haste-map/build/index.js @@ -0,0 +1,1110 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = exports.ModuleMap = exports.DuplicateError = void 0; +function _crypto() { + const data = require('crypto'); + _crypto = function () { + return data; + }; + return data; +} +function _events() { + const data = require('events'); + _events = function () { + return data; + }; + return data; +} +function _os() { + const data = require('os'); + _os = function () { + return data; + }; + return data; +} +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _v() { + const data = require('v8'); + _v = function () { + return data; + }; + return data; +} +function _gracefulFs() { + const data = require('graceful-fs'); + _gracefulFs = function () { + return data; + }; + return data; +} +function _jestRegexUtil() { + const data = require('jest-regex-util'); + _jestRegexUtil = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _jestWorker() { + const data = require('jest-worker'); + _jestWorker = function () { + return data; + }; + return data; +} +var _HasteFS = _interopRequireDefault(require('./HasteFS')); +var _ModuleMap = _interopRequireDefault(require('./ModuleMap')); +var _constants = _interopRequireDefault(require('./constants')); +var _node = require('./crawlers/node'); +var _watchman = require('./crawlers/watchman'); +var _getMockName = _interopRequireDefault(require('./getMockName')); +var fastPath = _interopRequireWildcard(require('./lib/fast_path')); +var _getPlatformExtension = _interopRequireDefault( + require('./lib/getPlatformExtension') +); +var _isWatchmanInstalled = _interopRequireDefault( + require('./lib/isWatchmanInstalled') +); +var _normalizePathSep = _interopRequireDefault( + require('./lib/normalizePathSep') +); +var _FSEventsWatcher = require('./watchers/FSEventsWatcher'); +var _NodeWatcher = _interopRequireDefault(require('./watchers/NodeWatcher')); +var _WatchmanWatcher = _interopRequireDefault( + require('./watchers/WatchmanWatcher') +); +var _worker = require('./worker'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// @ts-expect-error: not converted to TypeScript - it's a fork: https://github.com/facebook/jest/pull/10919 + +// @ts-expect-error: not converted to TypeScript - it's a fork: https://github.com/facebook/jest/pull/5387 + +// TypeScript doesn't like us importing from outside `rootDir`, but it doesn't +// understand `require`. +const {version: VERSION} = require('../package.json'); +const ModuleMap = _ModuleMap.default; +exports.ModuleMap = ModuleMap; +const CHANGE_INTERVAL = 30; +const MAX_WAIT_TIME = 240000; +const NODE_MODULES = `${path().sep}node_modules${path().sep}`; +const PACKAGE_JSON = `${path().sep}package.json`; +const VCS_DIRECTORIES = ['.git', '.hg'] + .map(vcs => + (0, _jestRegexUtil().escapePathForRegex)(path().sep + vcs + path().sep) + ) + .join('|'); +function invariant(condition, message) { + if (!condition) { + throw new Error(message); + } +} + +/** + * HasteMap is a JavaScript implementation of Facebook's haste module system. + * + * This implementation is inspired by https://github.com/facebook/node-haste + * and was built with for high-performance in large code repositories with + * hundreds of thousands of files. This implementation is scalable and provides + * predictable performance. + * + * Because the haste map creation and synchronization is critical to startup + * performance and most tasks are blocked by I/O this class makes heavy use of + * synchronous operations. It uses worker processes for parallelizing file + * access and metadata extraction. + * + * The data structures created by `jest-haste-map` can be used directly from the + * cache without further processing. The metadata objects in the `files` and + * `map` objects contain cross-references: a metadata object from one can look + * up the corresponding metadata object in the other map. Note that in most + * projects, the number of files will be greater than the number of haste + * modules one module can refer to many files based on platform extensions. + * + * type HasteMap = { + * clocks: WatchmanClocks, + * files: {[filepath: string]: FileMetaData}, + * map: {[id: string]: ModuleMapItem}, + * mocks: {[id: string]: string}, + * } + * + * // Watchman clocks are used for query synchronization and file system deltas. + * type WatchmanClocks = {[filepath: string]: string}; + * + * type FileMetaData = { + * id: ?string, // used to look up module metadata objects in `map`. + * mtime: number, // check for outdated files. + * size: number, // size of the file in bytes. + * visited: boolean, // whether the file has been parsed or not. + * dependencies: Array, // all relative dependencies of this file. + * sha1: ?string, // SHA-1 of the file, if requested via options. + * }; + * + * // Modules can be targeted to a specific platform based on the file name. + * // Example: platform.ios.js and Platform.android.js will both map to the same + * // `Platform` module. The platform should be specified during resolution. + * type ModuleMapItem = {[platform: string]: ModuleMetaData}; + * + * // + * type ModuleMetaData = { + * path: string, // the path to look up the file object in `files`. + * type: string, // the module type (either `package` or `module`). + * }; + * + * Note that the data structures described above are conceptual only. The actual + * implementation uses arrays and constant keys for metadata storage. Instead of + * `{id: 'flatMap', mtime: 3421, size: 42, visited: true, dependencies: []}` the real + * representation is similar to `['flatMap', 3421, 42, 1, []]` to save storage space + * and reduce parse and write time of a big JSON blob. + * + * The HasteMap is created as follows: + * 1. read data from the cache or create an empty structure. + * + * 2. crawl the file system. + * * empty cache: crawl the entire file system. + * * cache available: + * * if watchman is available: get file system delta changes. + * * if watchman is unavailable: crawl the entire file system. + * * build metadata objects for every file. This builds the `files` part of + * the `HasteMap`. + * + * 3. parse and extract metadata from changed files. + * * this is done in parallel over worker processes to improve performance. + * * the worst case is to parse all files. + * * the best case is no file system access and retrieving all data from + * the cache. + * * the average case is a small number of changed files. + * + * 4. serialize the new `HasteMap` in a cache file. + * Worker processes can directly access the cache through `HasteMap.read()`. + * + */ +class HasteMap extends _events().EventEmitter { + _buildPromise = null; + _cachePath = ''; + _changeInterval; + _console; + _isWatchmanInstalledPromise = null; + _options; + _watchers = []; + _worker = null; + static getStatic(config) { + if (config.haste.hasteMapModulePath) { + return require(config.haste.hasteMapModulePath); + } + return HasteMap; + } + static async create(options) { + if (options.hasteMapModulePath) { + const CustomHasteMap = require(options.hasteMapModulePath); + return new CustomHasteMap(options); + } + const hasteMap = new HasteMap(options); + await hasteMap.setupCachePath(options); + return hasteMap; + } + constructor(options) { + super(); + this._options = { + cacheDirectory: options.cacheDirectory || (0, _os().tmpdir)(), + computeDependencies: options.computeDependencies ?? true, + computeSha1: options.computeSha1 || false, + dependencyExtractor: options.dependencyExtractor || null, + enableSymlinks: options.enableSymlinks || false, + extensions: options.extensions, + forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI, + hasteImplModulePath: options.hasteImplModulePath, + id: options.id, + maxWorkers: options.maxWorkers, + mocksPattern: options.mocksPattern + ? new RegExp(options.mocksPattern) + : null, + platforms: options.platforms, + resetCache: options.resetCache, + retainAllFiles: options.retainAllFiles, + rootDir: options.rootDir, + roots: Array.from(new Set(options.roots)), + skipPackageJson: !!options.skipPackageJson, + throwOnModuleCollision: !!options.throwOnModuleCollision, + useWatchman: options.useWatchman ?? true, + watch: !!options.watch + }; + this._console = options.console || globalThis.console; + if (options.ignorePattern) { + if (options.ignorePattern instanceof RegExp) { + this._options.ignorePattern = new RegExp( + options.ignorePattern.source.concat(`|${VCS_DIRECTORIES}`), + options.ignorePattern.flags + ); + } else { + throw new Error( + 'jest-haste-map: the `ignorePattern` option must be a RegExp' + ); + } + } else { + this._options.ignorePattern = new RegExp(VCS_DIRECTORIES); + } + if (this._options.enableSymlinks && this._options.useWatchman) { + throw new Error( + 'jest-haste-map: enableSymlinks config option was set, but ' + + 'is incompatible with watchman.\n' + + 'Set either `enableSymlinks` to false or `useWatchman` to false.' + ); + } + } + async setupCachePath(options) { + const rootDirHash = (0, _crypto().createHash)('sha1') + .update(options.rootDir) + .digest('hex') + .substring(0, 32); + let hasteImplHash = ''; + let dependencyExtractorHash = ''; + if (options.hasteImplModulePath) { + const hasteImpl = require(options.hasteImplModulePath); + if (hasteImpl.getCacheKey) { + hasteImplHash = String(hasteImpl.getCacheKey()); + } + } + if (options.dependencyExtractor) { + const dependencyExtractor = await (0, _jestUtil().requireOrImportModule)( + options.dependencyExtractor, + false + ); + if (dependencyExtractor.getCacheKey) { + dependencyExtractorHash = String(dependencyExtractor.getCacheKey()); + } + } + this._cachePath = HasteMap.getCacheFilePath( + this._options.cacheDirectory, + `haste-map-${this._options.id}-${rootDirHash}`, + VERSION, + this._options.id, + this._options.roots + .map(root => fastPath.relative(options.rootDir, root)) + .join(':'), + this._options.extensions.join(':'), + this._options.platforms.join(':'), + this._options.computeSha1.toString(), + options.mocksPattern || '', + (options.ignorePattern || '').toString(), + hasteImplHash, + dependencyExtractorHash, + this._options.computeDependencies.toString() + ); + } + static getCacheFilePath(tmpdir, id, ...extra) { + const hash = (0, _crypto().createHash)('sha1').update(extra.join('')); + return path().join( + tmpdir, + `${id.replace(/\W/g, '-')}-${hash.digest('hex').substring(0, 32)}` + ); + } + static getModuleMapFromJSON(json) { + return _ModuleMap.default.fromJSON(json); + } + getCacheFilePath() { + return this._cachePath; + } + build() { + if (!this._buildPromise) { + this._buildPromise = (async () => { + const data = await this._buildFileMap(); + + // Persist when we don't know if files changed (changedFiles undefined) + // or when we know a file was changed or deleted. + let hasteMap; + if ( + data.changedFiles === undefined || + data.changedFiles.size > 0 || + data.removedFiles.size > 0 + ) { + hasteMap = await this._buildHasteMap(data); + this._persist(hasteMap); + } else { + hasteMap = data.hasteMap; + } + const rootDir = this._options.rootDir; + const hasteFS = new _HasteFS.default({ + files: hasteMap.files, + rootDir + }); + const moduleMap = new _ModuleMap.default({ + duplicates: hasteMap.duplicates, + map: hasteMap.map, + mocks: hasteMap.mocks, + rootDir + }); + const __hasteMapForTest = + (process.env.NODE_ENV === 'test' && hasteMap) || null; + await this._watch(hasteMap); + return { + __hasteMapForTest, + hasteFS, + moduleMap + }; + })(); + } + return this._buildPromise; + } + + /** + * 1. read data from the cache or create an empty structure. + */ + read() { + let hasteMap; + try { + hasteMap = (0, _v().deserialize)( + (0, _gracefulFs().readFileSync)(this._cachePath) + ); + } catch { + hasteMap = this._createEmptyMap(); + } + return hasteMap; + } + readModuleMap() { + const data = this.read(); + return new _ModuleMap.default({ + duplicates: data.duplicates, + map: data.map, + mocks: data.mocks, + rootDir: this._options.rootDir + }); + } + + /** + * 2. crawl the file system. + */ + async _buildFileMap() { + let hasteMap; + try { + const read = this._options.resetCache ? this._createEmptyMap : this.read; + hasteMap = read.call(this); + } catch { + hasteMap = this._createEmptyMap(); + } + return this._crawl(hasteMap); + } + + /** + * 3. parse and extract metadata from changed files. + */ + _processFile(hasteMap, map, mocks, filePath, workerOptions) { + const rootDir = this._options.rootDir; + const setModule = (id, module) => { + let moduleMap = map.get(id); + if (!moduleMap) { + moduleMap = Object.create(null); + map.set(id, moduleMap); + } + const platform = + (0, _getPlatformExtension.default)( + module[_constants.default.PATH], + this._options.platforms + ) || _constants.default.GENERIC_PLATFORM; + const existingModule = moduleMap[platform]; + if ( + existingModule && + existingModule[_constants.default.PATH] !== + module[_constants.default.PATH] + ) { + const method = this._options.throwOnModuleCollision ? 'error' : 'warn'; + this._console[method]( + [ + `jest-haste-map: Haste module naming collision: ${id}`, + ' The following files share their name; please adjust your hasteImpl:', + ` * ${path().sep}${ + existingModule[_constants.default.PATH] + }`, + ` * ${path().sep}${module[_constants.default.PATH]}`, + '' + ].join('\n') + ); + if (this._options.throwOnModuleCollision) { + throw new DuplicateError( + existingModule[_constants.default.PATH], + module[_constants.default.PATH] + ); + } + + // We do NOT want consumers to use a module that is ambiguous. + delete moduleMap[platform]; + if (Object.keys(moduleMap).length === 1) { + map.delete(id); + } + let dupsByPlatform = hasteMap.duplicates.get(id); + if (dupsByPlatform == null) { + dupsByPlatform = new Map(); + hasteMap.duplicates.set(id, dupsByPlatform); + } + const dups = new Map([ + [module[_constants.default.PATH], module[_constants.default.TYPE]], + [ + existingModule[_constants.default.PATH], + existingModule[_constants.default.TYPE] + ] + ]); + dupsByPlatform.set(platform, dups); + return; + } + const dupsByPlatform = hasteMap.duplicates.get(id); + if (dupsByPlatform != null) { + const dups = dupsByPlatform.get(platform); + if (dups != null) { + dups.set( + module[_constants.default.PATH], + module[_constants.default.TYPE] + ); + } + return; + } + moduleMap[platform] = module; + }; + const relativeFilePath = fastPath.relative(rootDir, filePath); + const fileMetadata = hasteMap.files.get(relativeFilePath); + if (!fileMetadata) { + throw new Error( + 'jest-haste-map: File to process was not found in the haste map.' + ); + } + const moduleMetadata = hasteMap.map.get( + fileMetadata[_constants.default.ID] + ); + const computeSha1 = + this._options.computeSha1 && !fileMetadata[_constants.default.SHA1]; + + // Callback called when the response from the worker is successful. + const workerReply = metadata => { + // `1` for truthy values instead of `true` to save cache space. + fileMetadata[_constants.default.VISITED] = 1; + const metadataId = metadata.id; + const metadataModule = metadata.module; + if (metadataId && metadataModule) { + fileMetadata[_constants.default.ID] = metadataId; + setModule(metadataId, metadataModule); + } + fileMetadata[_constants.default.DEPENDENCIES] = metadata.dependencies + ? metadata.dependencies.join(_constants.default.DEPENDENCY_DELIM) + : ''; + if (computeSha1) { + fileMetadata[_constants.default.SHA1] = metadata.sha1; + } + }; + + // Callback called when the response from the worker is an error. + const workerError = error => { + if (typeof error !== 'object' || !error.message || !error.stack) { + error = new Error(error); + error.stack = ''; // Remove stack for stack-less errors. + } + + if (!['ENOENT', 'EACCES'].includes(error.code)) { + throw error; + } + + // If a file cannot be read we remove it from the file list and + // ignore the failure silently. + hasteMap.files.delete(relativeFilePath); + }; + + // If we retain all files in the virtual HasteFS representation, we avoid + // reading them if they aren't important (node_modules). + if (this._options.retainAllFiles && filePath.includes(NODE_MODULES)) { + if (computeSha1) { + return this._getWorker(workerOptions) + .getSha1({ + computeDependencies: this._options.computeDependencies, + computeSha1, + dependencyExtractor: this._options.dependencyExtractor, + filePath, + hasteImplModulePath: this._options.hasteImplModulePath, + rootDir + }) + .then(workerReply, workerError); + } + return null; + } + if ( + this._options.mocksPattern && + this._options.mocksPattern.test(filePath) + ) { + const mockPath = (0, _getMockName.default)(filePath); + const existingMockPath = mocks.get(mockPath); + if (existingMockPath) { + const secondMockPath = fastPath.relative(rootDir, filePath); + if (existingMockPath !== secondMockPath) { + const method = this._options.throwOnModuleCollision + ? 'error' + : 'warn'; + this._console[method]( + [ + `jest-haste-map: duplicate manual mock found: ${mockPath}`, + ' The following files share their name; please delete one of them:', + ` * ${path().sep}${existingMockPath}`, + ` * ${path().sep}${secondMockPath}`, + '' + ].join('\n') + ); + if (this._options.throwOnModuleCollision) { + throw new DuplicateError(existingMockPath, secondMockPath); + } + } + } + mocks.set(mockPath, relativeFilePath); + } + if (fileMetadata[_constants.default.VISITED]) { + if (!fileMetadata[_constants.default.ID]) { + return null; + } + if (moduleMetadata != null) { + const platform = + (0, _getPlatformExtension.default)( + filePath, + this._options.platforms + ) || _constants.default.GENERIC_PLATFORM; + const module = moduleMetadata[platform]; + if (module == null) { + return null; + } + const moduleId = fileMetadata[_constants.default.ID]; + let modulesByPlatform = map.get(moduleId); + if (!modulesByPlatform) { + modulesByPlatform = Object.create(null); + map.set(moduleId, modulesByPlatform); + } + modulesByPlatform[platform] = module; + return null; + } + } + return this._getWorker(workerOptions) + .worker({ + computeDependencies: this._options.computeDependencies, + computeSha1, + dependencyExtractor: this._options.dependencyExtractor, + filePath, + hasteImplModulePath: this._options.hasteImplModulePath, + rootDir + }) + .then(workerReply, workerError); + } + _buildHasteMap(data) { + const {removedFiles, changedFiles, hasteMap} = data; + + // If any files were removed or we did not track what files changed, process + // every file looking for changes. Otherwise, process only changed files. + let map; + let mocks; + let filesToProcess; + if (changedFiles === undefined || removedFiles.size) { + map = new Map(); + mocks = new Map(); + filesToProcess = hasteMap.files; + } else { + map = hasteMap.map; + mocks = hasteMap.mocks; + filesToProcess = changedFiles; + } + for (const [relativeFilePath, fileMetadata] of removedFiles) { + this._recoverDuplicates( + hasteMap, + relativeFilePath, + fileMetadata[_constants.default.ID] + ); + } + const promises = []; + for (const relativeFilePath of filesToProcess.keys()) { + if ( + this._options.skipPackageJson && + relativeFilePath.endsWith(PACKAGE_JSON) + ) { + continue; + } + // SHA-1, if requested, should already be present thanks to the crawler. + const filePath = fastPath.resolve( + this._options.rootDir, + relativeFilePath + ); + const promise = this._processFile(hasteMap, map, mocks, filePath); + if (promise) { + promises.push(promise); + } + } + return Promise.all(promises).then( + () => { + this._cleanup(); + hasteMap.map = map; + hasteMap.mocks = mocks; + return hasteMap; + }, + error => { + this._cleanup(); + throw error; + } + ); + } + _cleanup() { + const worker = this._worker; + if (worker && 'end' in worker) { + worker.end(); + } + this._worker = null; + } + + /** + * 4. serialize the new `HasteMap` in a cache file. + */ + _persist(hasteMap) { + (0, _gracefulFs().writeFileSync)( + this._cachePath, + (0, _v().serialize)(hasteMap) + ); + } + + /** + * Creates workers or parses files and extracts metadata in-process. + */ + _getWorker( + options = { + forceInBand: false + } + ) { + if (!this._worker) { + if (options.forceInBand || this._options.maxWorkers <= 1) { + this._worker = { + getSha1: _worker.getSha1, + worker: _worker.worker + }; + } else { + this._worker = new (_jestWorker().Worker)(require.resolve('./worker'), { + exposedMethods: ['getSha1', 'worker'], + forkOptions: { + serialization: 'json' + }, + maxRetries: 3, + numWorkers: this._options.maxWorkers + }); + } + } + return this._worker; + } + async _crawl(hasteMap) { + const options = this._options; + const ignore = this._ignore.bind(this); + const crawl = (await this._shouldUseWatchman()) + ? _watchman.watchmanCrawl + : _node.nodeCrawl; + const crawlerOptions = { + computeSha1: options.computeSha1, + data: hasteMap, + enableSymlinks: options.enableSymlinks, + extensions: options.extensions, + forceNodeFilesystemAPI: options.forceNodeFilesystemAPI, + ignore, + rootDir: options.rootDir, + roots: options.roots + }; + const retry = error => { + if (crawl === _watchman.watchmanCrawl) { + this._console.warn( + 'jest-haste-map: Watchman crawl failed. Retrying once with node ' + + 'crawler.\n' + + " Usually this happens when watchman isn't running. Create an " + + "empty `.watchmanconfig` file in your project's root folder or " + + 'initialize a git or hg repository in your project.\n' + + ` ${error}` + ); + return (0, _node.nodeCrawl)(crawlerOptions).catch(e => { + throw new Error( + 'Crawler retry failed:\n' + + ` Original error: ${error.message}\n` + + ` Retry error: ${e.message}\n` + ); + }); + } + throw error; + }; + try { + return await crawl(crawlerOptions); + } catch (error) { + return retry(error); + } + } + + /** + * Watch mode + */ + async _watch(hasteMap) { + if (!this._options.watch) { + return Promise.resolve(); + } + + // In watch mode, we'll only warn about module collisions and we'll retain + // all files, even changes to node_modules. + this._options.throwOnModuleCollision = false; + this._options.retainAllFiles = true; + + // WatchmanWatcher > FSEventsWatcher > sane.NodeWatcher + const Watcher = (await this._shouldUseWatchman()) + ? _WatchmanWatcher.default + : _FSEventsWatcher.FSEventsWatcher.isSupported() + ? _FSEventsWatcher.FSEventsWatcher + : _NodeWatcher.default; + const extensions = this._options.extensions; + const ignorePattern = this._options.ignorePattern; + const rootDir = this._options.rootDir; + let changeQueue = Promise.resolve(); + let eventsQueue = []; + // We only need to copy the entire haste map once on every "frame". + let mustCopy = true; + const createWatcher = root => { + const watcher = new Watcher(root, { + dot: true, + glob: extensions.map(extension => `**/*.${extension}`), + ignored: ignorePattern + }); + return new Promise((resolve, reject) => { + const rejectTimeout = setTimeout( + () => reject(new Error('Failed to start watch mode.')), + MAX_WAIT_TIME + ); + watcher.once('ready', () => { + clearTimeout(rejectTimeout); + watcher.on('all', onChange); + resolve(watcher); + }); + }); + }; + const emitChange = () => { + if (eventsQueue.length) { + mustCopy = true; + const changeEvent = { + eventsQueue, + hasteFS: new _HasteFS.default({ + files: hasteMap.files, + rootDir + }), + moduleMap: new _ModuleMap.default({ + duplicates: hasteMap.duplicates, + map: hasteMap.map, + mocks: hasteMap.mocks, + rootDir + }) + }; + this.emit('change', changeEvent); + eventsQueue = []; + } + }; + const onChange = (type, filePath, root, stat) => { + filePath = path().join(root, (0, _normalizePathSep.default)(filePath)); + if ( + (stat && stat.isDirectory()) || + this._ignore(filePath) || + !extensions.some(extension => filePath.endsWith(extension)) + ) { + return; + } + const relativeFilePath = fastPath.relative(rootDir, filePath); + const fileMetadata = hasteMap.files.get(relativeFilePath); + + // The file has been accessed, not modified + if ( + type === 'change' && + fileMetadata && + stat && + fileMetadata[_constants.default.MTIME] === stat.mtime.getTime() + ) { + return; + } + changeQueue = changeQueue + .then(() => { + // If we get duplicate events for the same file, ignore them. + if ( + eventsQueue.find( + event => + event.type === type && + event.filePath === filePath && + ((!event.stat && !stat) || + (!!event.stat && + !!stat && + event.stat.mtime.getTime() === stat.mtime.getTime())) + ) + ) { + return null; + } + if (mustCopy) { + mustCopy = false; + hasteMap = { + clocks: new Map(hasteMap.clocks), + duplicates: new Map(hasteMap.duplicates), + files: new Map(hasteMap.files), + map: new Map(hasteMap.map), + mocks: new Map(hasteMap.mocks) + }; + } + const add = () => { + eventsQueue.push({ + filePath, + stat, + type + }); + return null; + }; + const fileMetadata = hasteMap.files.get(relativeFilePath); + + // If it's not an addition, delete the file and all its metadata + if (fileMetadata != null) { + const moduleName = fileMetadata[_constants.default.ID]; + const platform = + (0, _getPlatformExtension.default)( + filePath, + this._options.platforms + ) || _constants.default.GENERIC_PLATFORM; + hasteMap.files.delete(relativeFilePath); + let moduleMap = hasteMap.map.get(moduleName); + if (moduleMap != null) { + // We are forced to copy the object because jest-haste-map exposes + // the map as an immutable entity. + moduleMap = copy(moduleMap); + delete moduleMap[platform]; + if (Object.keys(moduleMap).length === 0) { + hasteMap.map.delete(moduleName); + } else { + hasteMap.map.set(moduleName, moduleMap); + } + } + if ( + this._options.mocksPattern && + this._options.mocksPattern.test(filePath) + ) { + const mockName = (0, _getMockName.default)(filePath); + hasteMap.mocks.delete(mockName); + } + this._recoverDuplicates(hasteMap, relativeFilePath, moduleName); + } + + // If the file was added or changed, + // parse it and update the haste map. + if (type === 'add' || type === 'change') { + invariant( + stat, + 'since the file exists or changed, it should have stats' + ); + const fileMetadata = [ + '', + stat.mtime.getTime(), + stat.size, + 0, + '', + null + ]; + hasteMap.files.set(relativeFilePath, fileMetadata); + const promise = this._processFile( + hasteMap, + hasteMap.map, + hasteMap.mocks, + filePath, + { + forceInBand: true + } + ); + // Cleanup + this._cleanup(); + if (promise) { + return promise.then(add); + } else { + // If a file in node_modules has changed, + // emit an event regardless. + add(); + } + } else { + add(); + } + return null; + }) + .catch(error => { + this._console.error( + `jest-haste-map: watch error:\n ${error.stack}\n` + ); + }); + }; + this._changeInterval = setInterval(emitChange, CHANGE_INTERVAL); + return Promise.all(this._options.roots.map(createWatcher)).then( + watchers => { + this._watchers = watchers; + } + ); + } + + /** + * This function should be called when the file under `filePath` is removed + * or changed. When that happens, we want to figure out if that file was + * part of a group of files that had the same ID. If it was, we want to + * remove it from the group. Furthermore, if there is only one file + * remaining in the group, then we want to restore that single file as the + * correct resolution for its ID, and cleanup the duplicates index. + */ + _recoverDuplicates(hasteMap, relativeFilePath, moduleName) { + let dupsByPlatform = hasteMap.duplicates.get(moduleName); + if (dupsByPlatform == null) { + return; + } + const platform = + (0, _getPlatformExtension.default)( + relativeFilePath, + this._options.platforms + ) || _constants.default.GENERIC_PLATFORM; + let dups = dupsByPlatform.get(platform); + if (dups == null) { + return; + } + dupsByPlatform = copyMap(dupsByPlatform); + hasteMap.duplicates.set(moduleName, dupsByPlatform); + dups = copyMap(dups); + dupsByPlatform.set(platform, dups); + dups.delete(relativeFilePath); + if (dups.size !== 1) { + return; + } + const uniqueModule = dups.entries().next().value; + if (!uniqueModule) { + return; + } + let dedupMap = hasteMap.map.get(moduleName); + if (!dedupMap) { + dedupMap = Object.create(null); + hasteMap.map.set(moduleName, dedupMap); + } + dedupMap[platform] = uniqueModule; + dupsByPlatform.delete(platform); + if (dupsByPlatform.size === 0) { + hasteMap.duplicates.delete(moduleName); + } + } + async end() { + if (this._changeInterval) { + clearInterval(this._changeInterval); + } + if (!this._watchers.length) { + return; + } + await Promise.all(this._watchers.map(watcher => watcher.close())); + this._watchers = []; + } + + /** + * Helpers + */ + _ignore(filePath) { + const ignorePattern = this._options.ignorePattern; + const ignoreMatched = + ignorePattern instanceof RegExp + ? ignorePattern.test(filePath) + : ignorePattern && ignorePattern(filePath); + return ( + ignoreMatched || + (!this._options.retainAllFiles && filePath.includes(NODE_MODULES)) + ); + } + async _shouldUseWatchman() { + if (!this._options.useWatchman) { + return false; + } + if (!this._isWatchmanInstalledPromise) { + this._isWatchmanInstalledPromise = (0, _isWatchmanInstalled.default)(); + } + return this._isWatchmanInstalledPromise; + } + _createEmptyMap() { + return { + clocks: new Map(), + duplicates: new Map(), + files: new Map(), + map: new Map(), + mocks: new Map() + }; + } + static H = _constants.default; +} +class DuplicateError extends Error { + mockPath1; + mockPath2; + constructor(mockPath1, mockPath2) { + super('Duplicated files or mocks. Please check the console for more info'); + this.mockPath1 = mockPath1; + this.mockPath2 = mockPath2; + } +} +exports.DuplicateError = DuplicateError; +function copy(object) { + return Object.assign(Object.create(null), object); +} +function copyMap(input) { + return new Map(input); +} + +// Export the smallest API surface required by Jest + +const JestHasteMap = HasteMap; +var _default = JestHasteMap; +exports.default = _default; diff --git a/node_modules/jest-haste-map/build/lib/dependencyExtractor.js b/node_modules/jest-haste-map/build/lib/dependencyExtractor.js new file mode 100644 index 0000000..10f752c --- /dev/null +++ b/node_modules/jest-haste-map/build/lib/dependencyExtractor.js @@ -0,0 +1,84 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.extractor = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const NOT_A_DOT = '(? `([\`'"])([^'"\`]*?)(?:\\${pos})`; +const WORD_SEPARATOR = '\\b'; +const LEFT_PARENTHESIS = '\\('; +const RIGHT_PARENTHESIS = '\\)'; +const WHITESPACE = '\\s*'; +const OPTIONAL_COMMA = '(:?,\\s*)?'; +function createRegExp(parts, flags) { + return new RegExp(parts.join(''), flags); +} +function alternatives(...parts) { + return `(?:${parts.join('|')})`; +} +function functionCallStart(...names) { + return [ + NOT_A_DOT, + WORD_SEPARATOR, + alternatives(...names), + WHITESPACE, + LEFT_PARENTHESIS, + WHITESPACE + ]; +} +const BLOCK_COMMENT_RE = /\/\*[^]*?\*\//g; +const LINE_COMMENT_RE = /\/\/.*/g; +const REQUIRE_OR_DYNAMIC_IMPORT_RE = createRegExp( + [ + ...functionCallStart('require', 'import'), + CAPTURE_STRING_LITERAL(1), + WHITESPACE, + OPTIONAL_COMMA, + RIGHT_PARENTHESIS + ], + 'g' +); +const IMPORT_OR_EXPORT_RE = createRegExp( + [ + '\\b(?:import|export)\\s+(?!type(?:of)?\\s+)(?:[^\'"]+\\s+from\\s+)?', + CAPTURE_STRING_LITERAL(1) + ], + 'g' +); +const JEST_EXTENSIONS_RE = createRegExp( + [ + ...functionCallStart( + 'jest\\s*\\.\\s*(?:requireActual|requireMock|genMockFromModule|createMockFromModule)' + ), + CAPTURE_STRING_LITERAL(1), + WHITESPACE, + OPTIONAL_COMMA, + RIGHT_PARENTHESIS + ], + 'g' +); +const extractor = { + extract(code) { + const dependencies = new Set(); + const addDependency = (match, _, dep) => { + dependencies.add(dep); + return match; + }; + code + .replace(BLOCK_COMMENT_RE, '') + .replace(LINE_COMMENT_RE, '') + .replace(IMPORT_OR_EXPORT_RE, addDependency) + .replace(REQUIRE_OR_DYNAMIC_IMPORT_RE, addDependency) + .replace(JEST_EXTENSIONS_RE, addDependency); + return dependencies; + } +}; +exports.extractor = extractor; diff --git a/node_modules/jest-haste-map/build/lib/fast_path.js b/node_modules/jest-haste-map/build/lib/fast_path.js new file mode 100644 index 0000000..0a93460 --- /dev/null +++ b/node_modules/jest-haste-map/build/lib/fast_path.js @@ -0,0 +1,76 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.relative = relative; +exports.resolve = resolve; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// rootDir and filename must be absolute paths (resolved) +function relative(rootDir, filename) { + return filename.indexOf(rootDir + path().sep) === 0 + ? filename.substring(rootDir.length + 1) + : path().relative(rootDir, filename); +} +const INDIRECTION_FRAGMENT = `..${path().sep}`; + +// rootDir must be an absolute path and relativeFilename must be simple +// (e.g.: foo/bar or ../foo/bar, but never ./foo or foo/../bar) +function resolve(rootDir, relativeFilename) { + return relativeFilename.indexOf(INDIRECTION_FRAGMENT) === 0 + ? path().resolve(rootDir, relativeFilename) + : rootDir + path().sep + relativeFilename; +} diff --git a/node_modules/jest-haste-map/build/lib/getPlatformExtension.js b/node_modules/jest-haste-map/build/lib/getPlatformExtension.js new file mode 100644 index 0000000..fea58e2 --- /dev/null +++ b/node_modules/jest-haste-map/build/lib/getPlatformExtension.js @@ -0,0 +1,30 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = getPlatformExtension; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const SUPPORTED_PLATFORM_EXTS = new Set(['android', 'ios', 'native', 'web']); + +// Extract platform extension: index.ios.js -> ios +function getPlatformExtension(file, platforms) { + const last = file.lastIndexOf('.'); + const secondToLast = file.lastIndexOf('.', last - 1); + if (secondToLast === -1) { + return null; + } + const platform = file.substring(secondToLast + 1, last); + // If an overriding platform array is passed, check that first + + if (platforms && platforms.indexOf(platform) !== -1) { + return platform; + } + return SUPPORTED_PLATFORM_EXTS.has(platform) ? platform : null; +} diff --git a/node_modules/jest-haste-map/build/lib/isWatchmanInstalled.js b/node_modules/jest-haste-map/build/lib/isWatchmanInstalled.js new file mode 100644 index 0000000..d21e573 --- /dev/null +++ b/node_modules/jest-haste-map/build/lib/isWatchmanInstalled.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = isWatchmanInstalled; +function _child_process() { + const data = require('child_process'); + _child_process = function () { + return data; + }; + return data; +} +function _util() { + const data = require('util'); + _util = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +async function isWatchmanInstalled() { + try { + await (0, _util().promisify)(_child_process().execFile)('watchman', [ + '--version' + ]); + return true; + } catch { + return false; + } +} diff --git a/node_modules/jest-haste-map/build/lib/normalizePathSep.js b/node_modules/jest-haste-map/build/lib/normalizePathSep.js new file mode 100644 index 0000000..b67f91c --- /dev/null +++ b/node_modules/jest-haste-map/build/lib/normalizePathSep.js @@ -0,0 +1,68 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +let normalizePathSep; +if (path().sep === '/') { + normalizePathSep = filePath => filePath; +} else { + normalizePathSep = filePath => filePath.replace(/\//g, path().sep); +} +var _default = normalizePathSep; +exports.default = _default; diff --git a/node_modules/jest-haste-map/build/types.js b/node_modules/jest-haste-map/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-haste-map/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-haste-map/build/watchers/FSEventsWatcher.js b/node_modules/jest-haste-map/build/watchers/FSEventsWatcher.js new file mode 100644 index 0000000..2a741c1 --- /dev/null +++ b/node_modules/jest-haste-map/build/watchers/FSEventsWatcher.js @@ -0,0 +1,244 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.FSEventsWatcher = void 0; +function _events() { + const data = require('events'); + _events = function () { + return data; + }; + return data; +} +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _anymatch() { + const data = _interopRequireDefault(require('anymatch')); + _anymatch = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _micromatch() { + const data = _interopRequireDefault(require('micromatch')); + _micromatch = function () { + return data; + }; + return data; +} +function _walker() { + const data = _interopRequireDefault(require('walker')); + _walker = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +// @ts-expect-error no types + +// eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error, @typescript-eslint/ban-ts-comment +// @ts-ignore: this is for CI which runs linux and might not have this +let fsevents = null; +try { + fsevents = require('fsevents'); +} catch { + // Optional dependency, only supported on Darwin. +} +const CHANGE_EVENT = 'change'; +const DELETE_EVENT = 'delete'; +const ADD_EVENT = 'add'; +const ALL_EVENT = 'all'; +/** + * Export `FSEventsWatcher` class. + * Watches `dir`. + */ +class FSEventsWatcher extends _events().EventEmitter { + root; + ignored; + glob; + dot; + hasIgnore; + doIgnore; + fsEventsWatchStopper; + _tracked; + static isSupported() { + return fsevents !== null; + } + static normalizeProxy(callback) { + return (filepath, stats) => callback(path().normalize(filepath), stats); + } + static recReaddir( + dir, + dirCallback, + fileCallback, + endCallback, + errorCallback, + ignored + ) { + (0, _walker().default)(dir) + .filterDir( + currentDir => !ignored || !(0, _anymatch().default)(ignored, currentDir) + ) + .on('dir', FSEventsWatcher.normalizeProxy(dirCallback)) + .on('file', FSEventsWatcher.normalizeProxy(fileCallback)) + .on('error', errorCallback) + .on('end', () => { + endCallback(); + }); + } + constructor(dir, opts) { + if (!fsevents) { + throw new Error( + '`fsevents` unavailable (this watcher can only be used on Darwin)' + ); + } + super(); + this.dot = opts.dot || false; + this.ignored = opts.ignored; + this.glob = Array.isArray(opts.glob) ? opts.glob : [opts.glob]; + this.hasIgnore = + Boolean(opts.ignored) && !(Array.isArray(opts) && opts.length > 0); + this.doIgnore = opts.ignored + ? (0, _anymatch().default)(opts.ignored) + : () => false; + this.root = path().resolve(dir); + this.fsEventsWatchStopper = fsevents.watch( + this.root, + this.handleEvent.bind(this) + ); + this._tracked = new Set(); + FSEventsWatcher.recReaddir( + this.root, + filepath => { + this._tracked.add(filepath); + }, + filepath => { + this._tracked.add(filepath); + }, + this.emit.bind(this, 'ready'), + this.emit.bind(this, 'error'), + this.ignored + ); + } + + /** + * End watching. + */ + async close(callback) { + await this.fsEventsWatchStopper(); + this.removeAllListeners(); + if (typeof callback === 'function') { + process.nextTick(callback.bind(null, null, true)); + } + } + isFileIncluded(relativePath) { + if (this.doIgnore(relativePath)) { + return false; + } + return this.glob.length + ? (0, _micromatch().default)([relativePath], this.glob, { + dot: this.dot + }).length > 0 + : this.dot || + (0, _micromatch().default)([relativePath], '**/*').length > 0; + } + handleEvent(filepath) { + const relativePath = path().relative(this.root, filepath); + if (!this.isFileIncluded(relativePath)) { + return; + } + fs().lstat(filepath, (error, stat) => { + if (error && error.code !== 'ENOENT') { + this.emit('error', error); + return; + } + if (error) { + // Ignore files that aren't tracked and don't exist. + if (!this._tracked.has(filepath)) { + return; + } + this._emit(DELETE_EVENT, relativePath); + this._tracked.delete(filepath); + return; + } + if (this._tracked.has(filepath)) { + this._emit(CHANGE_EVENT, relativePath, stat); + } else { + this._tracked.add(filepath); + this._emit(ADD_EVENT, relativePath, stat); + } + }); + } + + /** + * Emit events. + */ + _emit(type, file, stat) { + this.emit(type, file, this.root, stat); + this.emit(ALL_EVENT, type, file, this.root, stat); + } +} +exports.FSEventsWatcher = FSEventsWatcher; diff --git a/node_modules/jest-haste-map/build/watchers/NodeWatcher.js b/node_modules/jest-haste-map/build/watchers/NodeWatcher.js new file mode 100644 index 0000000..62cface --- /dev/null +++ b/node_modules/jest-haste-map/build/watchers/NodeWatcher.js @@ -0,0 +1,369 @@ +// vendored from https://github.com/amasad/sane/blob/64ff3a870c42e84f744086884bf55a4f9c22d376/src/node_watcher.js + +'use strict'; + +const EventEmitter = require('events').EventEmitter; +const fs = require('fs'); +const platform = require('os').platform(); +const path = require('path'); +const common = require('./common'); + +/** + * Constants + */ + +const DEFAULT_DELAY = common.DEFAULT_DELAY; +const CHANGE_EVENT = common.CHANGE_EVENT; +const DELETE_EVENT = common.DELETE_EVENT; +const ADD_EVENT = common.ADD_EVENT; +const ALL_EVENT = common.ALL_EVENT; + +/** + * Export `NodeWatcher` class. + * Watches `dir`. + * + * @class NodeWatcher + * @param {String} dir + * @param {Object} opts + * @public + */ + +module.exports = class NodeWatcher extends EventEmitter { + constructor(dir, opts) { + super(); + common.assignOptions(this, opts); + this.watched = Object.create(null); + this.changeTimers = Object.create(null); + this.dirRegistery = Object.create(null); + this.root = path.resolve(dir); + this.watchdir = this.watchdir.bind(this); + this.register = this.register.bind(this); + this.checkedEmitError = this.checkedEmitError.bind(this); + this.watchdir(this.root); + common.recReaddir( + this.root, + this.watchdir, + this.register, + this.emit.bind(this, 'ready'), + this.checkedEmitError, + this.ignored + ); + } + + /** + * Register files that matches our globs to know what to type of event to + * emit in the future. + * + * Registery looks like the following: + * + * dirRegister => Map { + * dirpath => Map { + * filename => true + * } + * } + * + * @param {string} filepath + * @return {boolean} whether or not we have registered the file. + * @private + */ + + register(filepath) { + const relativePath = path.relative(this.root, filepath); + if ( + !common.isFileIncluded(this.globs, this.dot, this.doIgnore, relativePath) + ) { + return false; + } + const dir = path.dirname(filepath); + if (!this.dirRegistery[dir]) { + this.dirRegistery[dir] = Object.create(null); + } + const filename = path.basename(filepath); + this.dirRegistery[dir][filename] = true; + return true; + } + + /** + * Removes a file from the registery. + * + * @param {string} filepath + * @private + */ + + unregister(filepath) { + const dir = path.dirname(filepath); + if (this.dirRegistery[dir]) { + const filename = path.basename(filepath); + delete this.dirRegistery[dir][filename]; + } + } + + /** + * Removes a dir from the registery. + * + * @param {string} dirpath + * @private + */ + + unregisterDir(dirpath) { + if (this.dirRegistery[dirpath]) { + delete this.dirRegistery[dirpath]; + } + } + + /** + * Checks if a file or directory exists in the registery. + * + * @param {string} fullpath + * @return {boolean} + * @private + */ + + registered(fullpath) { + const dir = path.dirname(fullpath); + return ( + this.dirRegistery[fullpath] || + (this.dirRegistery[dir] && + this.dirRegistery[dir][path.basename(fullpath)]) + ); + } + + /** + * Emit "error" event if it's not an ignorable event + * + * @param error + * @private + */ + checkedEmitError(error) { + if (!isIgnorableFileError(error)) { + this.emit('error', error); + } + } + + /** + * Watch a directory. + * + * @param {string} dir + * @private + */ + + watchdir(dir) { + if (this.watched[dir]) { + return; + } + const watcher = fs.watch( + dir, + { + persistent: true + }, + this.normalizeChange.bind(this, dir) + ); + this.watched[dir] = watcher; + watcher.on('error', this.checkedEmitError); + if (this.root !== dir) { + this.register(dir); + } + } + + /** + * Stop watching a directory. + * + * @param {string} dir + * @private + */ + + stopWatching(dir) { + if (this.watched[dir]) { + this.watched[dir].close(); + delete this.watched[dir]; + } + } + + /** + * End watching. + * + * @public + */ + + close() { + Object.keys(this.watched).forEach(this.stopWatching, this); + this.removeAllListeners(); + return Promise.resolve(); + } + + /** + * On some platforms, as pointed out on the fs docs (most likely just win32) + * the file argument might be missing from the fs event. Try to detect what + * change by detecting if something was deleted or the most recent file change. + * + * @param {string} dir + * @param {string} event + * @param {string} file + * @public + */ + + detectChangedFile(dir, event, callback) { + if (!this.dirRegistery[dir]) { + return; + } + let found = false; + let closest = { + mtime: 0 + }; + let c = 0; + Object.keys(this.dirRegistery[dir]).forEach(function (file, i, arr) { + fs.lstat(path.join(dir, file), (error, stat) => { + if (found) { + return; + } + if (error) { + if (isIgnorableFileError(error)) { + found = true; + callback(file); + } else { + this.emit('error', error); + } + } else { + if (stat.mtime > closest.mtime) { + stat.file = file; + closest = stat; + } + if (arr.length === ++c) { + callback(closest.file); + } + } + }); + }, this); + } + + /** + * Normalize fs events and pass it on to be processed. + * + * @param {string} dir + * @param {string} event + * @param {string} file + * @public + */ + + normalizeChange(dir, event, file) { + if (!file) { + this.detectChangedFile(dir, event, actualFile => { + if (actualFile) { + this.processChange(dir, event, actualFile); + } + }); + } else { + this.processChange(dir, event, path.normalize(file)); + } + } + + /** + * Process changes. + * + * @param {string} dir + * @param {string} event + * @param {string} file + * @public + */ + + processChange(dir, event, file) { + const fullPath = path.join(dir, file); + const relativePath = path.join(path.relative(this.root, dir), file); + fs.lstat(fullPath, (error, stat) => { + if (error && error.code !== 'ENOENT') { + this.emit('error', error); + } else if (!error && stat.isDirectory()) { + // win32 emits usless change events on dirs. + if (event !== 'change') { + this.watchdir(fullPath); + if ( + common.isFileIncluded( + this.globs, + this.dot, + this.doIgnore, + relativePath + ) + ) { + this.emitEvent(ADD_EVENT, relativePath, stat); + } + } + } else { + const registered = this.registered(fullPath); + if (error && error.code === 'ENOENT') { + this.unregister(fullPath); + this.stopWatching(fullPath); + this.unregisterDir(fullPath); + if (registered) { + this.emitEvent(DELETE_EVENT, relativePath); + } + } else if (registered) { + this.emitEvent(CHANGE_EVENT, relativePath, stat); + } else { + if (this.register(fullPath)) { + this.emitEvent(ADD_EVENT, relativePath, stat); + } + } + } + }); + } + + /** + * Triggers a 'change' event after debounding it to take care of duplicate + * events on os x. + * + * @private + */ + + emitEvent(type, file, stat) { + const key = `${type}-${file}`; + const addKey = `${ADD_EVENT}-${file}`; + if (type === CHANGE_EVENT && this.changeTimers[addKey]) { + // Ignore the change event that is immediately fired after an add event. + // (This happens on Linux). + return; + } + clearTimeout(this.changeTimers[key]); + this.changeTimers[key] = setTimeout(() => { + delete this.changeTimers[key]; + if (type === ADD_EVENT && stat.isDirectory()) { + // Recursively emit add events and watch for sub-files/folders + common.recReaddir( + path.resolve(this.root, file), + function emitAddDir(dir, stats) { + this.watchdir(dir); + this.rawEmitEvent(ADD_EVENT, path.relative(this.root, dir), stats); + }.bind(this), + function emitAddFile(file, stats) { + this.register(file); + this.rawEmitEvent(ADD_EVENT, path.relative(this.root, file), stats); + }.bind(this), + function endCallback() {}, + this.checkedEmitError, + this.ignored + ); + } else { + this.rawEmitEvent(type, file, stat); + } + }, DEFAULT_DELAY); + } + + /** + * Actually emit the events + */ + rawEmitEvent(type, file, stat) { + this.emit(type, file, this.root, stat); + this.emit(ALL_EVENT, type, file, this.root, stat); + } +}; +/** + * Determine if a given FS error can be ignored + * + * @private + */ +function isIgnorableFileError(error) { + return ( + error.code === 'ENOENT' || + // Workaround Windows node issue #4337. + (error.code === 'EPERM' && platform === 'win32') + ); +} diff --git a/node_modules/jest-haste-map/build/watchers/RecrawlWarning.js b/node_modules/jest-haste-map/build/watchers/RecrawlWarning.js new file mode 100644 index 0000000..5b1b6d3 --- /dev/null +++ b/node_modules/jest-haste-map/build/watchers/RecrawlWarning.js @@ -0,0 +1,49 @@ +// vendored from https://github.com/amasad/sane/blob/64ff3a870c42e84f744086884bf55a4f9c22d376/src/utils/recrawl-warning-dedupe.js + +'use strict'; + +class RecrawlWarning { + constructor(root, count) { + this.root = root; + this.count = count; + } + static findByRoot(root) { + for (let i = 0; i < this.RECRAWL_WARNINGS.length; i++) { + const warning = this.RECRAWL_WARNINGS[i]; + if (warning.root === root) { + return warning; + } + } + return undefined; + } + static isRecrawlWarningDupe(warningMessage) { + if (typeof warningMessage !== 'string') { + return false; + } + const match = warningMessage.match(this.REGEXP); + if (!match) { + return false; + } + const count = Number(match[1]); + const root = match[2]; + const warning = this.findByRoot(root); + if (warning) { + // only keep the highest count, assume count to either stay the same or + // increase. + if (warning.count >= count) { + return true; + } else { + // update the existing warning to the latest (highest) count + warning.count = count; + return false; + } + } else { + this.RECRAWL_WARNINGS.push(new RecrawlWarning(root, count)); + return false; + } + } +} +RecrawlWarning.RECRAWL_WARNINGS = []; +RecrawlWarning.REGEXP = + /Recrawled this watch (\d+) times, most recently because:\n([^:]+)/; +module.exports = RecrawlWarning; diff --git a/node_modules/jest-haste-map/build/watchers/WatchmanWatcher.js b/node_modules/jest-haste-map/build/watchers/WatchmanWatcher.js new file mode 100644 index 0000000..577157b --- /dev/null +++ b/node_modules/jest-haste-map/build/watchers/WatchmanWatcher.js @@ -0,0 +1,383 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = WatchmanWatcher; +function _assert() { + const data = require('assert'); + _assert = function () { + return data; + }; + return data; +} +function _events() { + const data = require('events'); + _events = function () { + return data; + }; + return data; +} +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _fbWatchman() { + const data = _interopRequireDefault(require('fb-watchman')); + _fbWatchman = function () { + return data; + }; + return data; +} +function _gracefulFs() { + const data = _interopRequireDefault(require('graceful-fs')); + _gracefulFs = function () { + return data; + }; + return data; +} +var _RecrawlWarning = _interopRequireDefault(require('./RecrawlWarning')); +var _common = _interopRequireDefault(require('./common')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const CHANGE_EVENT = _common.default.CHANGE_EVENT; +const DELETE_EVENT = _common.default.DELETE_EVENT; +const ADD_EVENT = _common.default.ADD_EVENT; +const ALL_EVENT = _common.default.ALL_EVENT; +const SUB_NAME = 'sane-sub'; + +/** + * Watches `dir`. + * + * @class PollWatcher + * @param String dir + * @param {Object} opts + * @public + */ + +function WatchmanWatcher(dir, opts) { + _common.default.assignOptions(this, opts); + this.root = path().resolve(dir); + this.init(); +} +Object.setPrototypeOf( + WatchmanWatcher.prototype, + _events().EventEmitter.prototype +); + +/** + * Run the watchman `watch` command on the root and subscribe to changes. + * + * @private + */ + +WatchmanWatcher.prototype.init = function () { + if (this.client) { + this.client.removeAllListeners(); + } + const self = this; + this.client = new (_fbWatchman().default.Client)(); + this.client.on('error', error => { + self.emit('error', error); + }); + this.client.on('subscription', this.handleChangeEvent.bind(this)); + this.client.on('end', () => { + console.warn('[sane] Warning: Lost connection to watchman, reconnecting..'); + self.init(); + }); + this.watchProjectInfo = null; + function getWatchRoot() { + return self.watchProjectInfo ? self.watchProjectInfo.root : self.root; + } + function onCapability(error, resp) { + if (handleError(self, error)) { + // The Watchman watcher is unusable on this system, we cannot continue + return; + } + handleWarning(resp); + self.capabilities = resp.capabilities; + if (self.capabilities.relative_root) { + self.client.command(['watch-project', getWatchRoot()], onWatchProject); + } else { + self.client.command(['watch', getWatchRoot()], onWatch); + } + } + function onWatchProject(error, resp) { + if (handleError(self, error)) { + return; + } + handleWarning(resp); + self.watchProjectInfo = { + relativePath: resp.relative_path ? resp.relative_path : '', + root: resp.watch + }; + self.client.command(['clock', getWatchRoot()], onClock); + } + function onWatch(error, resp) { + if (handleError(self, error)) { + return; + } + handleWarning(resp); + self.client.command(['clock', getWatchRoot()], onClock); + } + function onClock(error, resp) { + if (handleError(self, error)) { + return; + } + handleWarning(resp); + const options = { + fields: ['name', 'exists', 'new'], + since: resp.clock + }; + + // If the server has the wildmatch capability available it supports + // the recursive **/*.foo style match and we can offload our globs + // to the watchman server. This saves both on data size to be + // communicated back to us and compute for evaluating the globs + // in our node process. + if (self.capabilities.wildmatch) { + if (self.globs.length === 0) { + if (!self.dot) { + // Make sure we honor the dot option if even we're not using globs. + options.expression = [ + 'match', + '**', + 'wholename', + { + includedotfiles: false + } + ]; + } + } else { + options.expression = ['anyof']; + for (const i in self.globs) { + options.expression.push([ + 'match', + self.globs[i], + 'wholename', + { + includedotfiles: self.dot + } + ]); + } + } + } + if (self.capabilities.relative_root) { + options.relative_root = self.watchProjectInfo.relativePath; + } + self.client.command( + ['subscribe', getWatchRoot(), SUB_NAME, options], + onSubscribe + ); + } + function onSubscribe(error, resp) { + if (handleError(self, error)) { + return; + } + handleWarning(resp); + self.emit('ready'); + } + self.client.capabilityCheck( + { + optional: ['wildmatch', 'relative_root'] + }, + onCapability + ); +}; + +/** + * Handles a change event coming from the subscription. + * + * @param {Object} resp + * @private + */ + +WatchmanWatcher.prototype.handleChangeEvent = function (resp) { + _assert().strict.equal( + resp.subscription, + SUB_NAME, + 'Invalid subscription event.' + ); + if (resp.is_fresh_instance) { + this.emit('fresh_instance'); + } + if (resp.is_fresh_instance) { + this.emit('fresh_instance'); + } + if (Array.isArray(resp.files)) { + resp.files.forEach(this.handleFileChange, this); + } +}; + +/** + * Handles a single change event record. + * + * @param {Object} changeDescriptor + * @private + */ + +WatchmanWatcher.prototype.handleFileChange = function (changeDescriptor) { + const self = this; + let absPath; + let relativePath; + if (this.capabilities.relative_root) { + relativePath = changeDescriptor.name; + absPath = path().join( + this.watchProjectInfo.root, + this.watchProjectInfo.relativePath, + relativePath + ); + } else { + absPath = path().join(this.root, changeDescriptor.name); + relativePath = changeDescriptor.name; + } + if ( + !(self.capabilities.wildmatch && !this.hasIgnore) && + !_common.default.isFileIncluded( + this.globs, + this.dot, + this.doIgnore, + relativePath + ) + ) { + return; + } + if (!changeDescriptor.exists) { + self.emitEvent(DELETE_EVENT, relativePath, self.root); + } else { + _gracefulFs().default.lstat(absPath, (error, stat) => { + // Files can be deleted between the event and the lstat call + // the most reliable thing to do here is to ignore the event. + if (error && error.code === 'ENOENT') { + return; + } + if (handleError(self, error)) { + return; + } + const eventType = changeDescriptor.new ? ADD_EVENT : CHANGE_EVENT; + + // Change event on dirs are mostly useless. + if (!(eventType === CHANGE_EVENT && stat.isDirectory())) { + self.emitEvent(eventType, relativePath, self.root, stat); + } + }); + } +}; + +/** + * Dispatches the event. + * + * @param {string} eventType + * @param {string} filepath + * @param {string} root + * @param {fs.Stat} stat + * @private + */ + +WatchmanWatcher.prototype.emitEvent = function ( + eventType, + filepath, + root, + stat +) { + this.emit(eventType, filepath, root, stat); + this.emit(ALL_EVENT, eventType, filepath, root, stat); +}; + +/** + * Closes the watcher. + * + */ + +WatchmanWatcher.prototype.close = function () { + this.client.removeAllListeners(); + this.client.end(); + return Promise.resolve(); +}; + +/** + * Handles an error and returns true if exists. + * + * @param {WatchmanWatcher} self + * @param {Error} error + * @private + */ + +function handleError(self, error) { + if (error != null) { + self.emit('error', error); + return true; + } else { + return false; + } +} + +/** + * Handles a warning in the watchman resp object. + * + * @param {object} resp + * @private + */ + +function handleWarning(resp) { + if ('warning' in resp) { + if (_RecrawlWarning.default.isRecrawlWarningDupe(resp.warning)) { + return true; + } + console.warn(resp.warning); + return true; + } else { + return false; + } +} diff --git a/node_modules/jest-haste-map/build/watchers/common.js b/node_modules/jest-haste-map/build/watchers/common.js new file mode 100644 index 0000000..b8fa0c3 --- /dev/null +++ b/node_modules/jest-haste-map/build/watchers/common.js @@ -0,0 +1,111 @@ +// vendored from https://github.com/amasad/sane/blob/64ff3a870c42e84f744086884bf55a4f9c22d376/src/common.js + +'use strict'; + +const platform = require('os').platform(); +const path = require('path'); +const anymatch = require('anymatch'); +const micromatch = require('micromatch'); +const walker = require('walker'); + +/** + * Constants + */ + +exports.DEFAULT_DELAY = 100; +exports.CHANGE_EVENT = 'change'; +exports.DELETE_EVENT = 'delete'; +exports.ADD_EVENT = 'add'; +exports.ALL_EVENT = 'all'; + +/** + * Assigns options to the watcher. + * + * @param {NodeWatcher|PollWatcher|WatchmanWatcher} watcher + * @param {?object} opts + * @return {boolean} + * @public + */ + +exports.assignOptions = function (watcher, opts) { + opts = opts || {}; + watcher.globs = opts.glob || []; + watcher.dot = opts.dot || false; + watcher.ignored = opts.ignored || false; + if (!Array.isArray(watcher.globs)) { + watcher.globs = [watcher.globs]; + } + watcher.hasIgnore = + Boolean(opts.ignored) && !(Array.isArray(opts) && opts.length > 0); + watcher.doIgnore = opts.ignored ? anymatch(opts.ignored) : () => false; + if (opts.watchman && opts.watchmanPath) { + watcher.watchmanPath = opts.watchmanPath; + } + return opts; +}; + +/** + * Checks a file relative path against the globs array. + * + * @param {array} globs + * @param {string} relativePath + * @return {boolean} + * @public + */ + +exports.isFileIncluded = function (globs, dot, doIgnore, relativePath) { + if (doIgnore(relativePath)) { + return false; + } + return globs.length + ? micromatch.some(relativePath, globs, { + dot + }) + : dot || micromatch.some(relativePath, '**/*'); +}; + +/** + * Traverse a directory recursively calling `callback` on every directory. + * + * @param {string} dir + * @param {function} dirCallback + * @param {function} fileCallback + * @param {function} endCallback + * @param {*} ignored + * @public + */ + +exports.recReaddir = function ( + dir, + dirCallback, + fileCallback, + endCallback, + errorCallback, + ignored +) { + walker(dir) + .filterDir(currentDir => !anymatch(ignored, currentDir)) + .on('dir', normalizeProxy(dirCallback)) + .on('file', normalizeProxy(fileCallback)) + .on('error', errorCallback) + .on('end', () => { + if (platform === 'win32') { + setTimeout(endCallback, 1000); + } else { + endCallback(); + } + }); +}; + +/** + * Returns a callback that when called will normalize a path and call the + * original callback + * + * @param {function} callback + * @return {function} + * @private + */ + +function normalizeProxy(callback) { + return (filepath, stats) => callback(path.normalize(filepath), stats); +} diff --git a/node_modules/jest-haste-map/build/worker.js b/node_modules/jest-haste-map/build/worker.js new file mode 100644 index 0000000..b7579a3 --- /dev/null +++ b/node_modules/jest-haste-map/build/worker.js @@ -0,0 +1,180 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getSha1 = getSha1; +exports.worker = worker; +function _crypto() { + const data = require('crypto'); + _crypto = function () { + return data; + }; + return data; +} +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _blacklist = _interopRequireDefault(require('./blacklist')); +var _constants = _interopRequireDefault(require('./constants')); +var _dependencyExtractor = require('./lib/dependencyExtractor'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const PACKAGE_JSON = `${path().sep}package.json`; +let hasteImpl = null; +let hasteImplModulePath = null; +function sha1hex(content) { + return (0, _crypto().createHash)('sha1').update(content).digest('hex'); +} +async function worker(data) { + if ( + data.hasteImplModulePath && + data.hasteImplModulePath !== hasteImplModulePath + ) { + if (hasteImpl) { + throw new Error('jest-haste-map: hasteImplModulePath changed'); + } + hasteImplModulePath = data.hasteImplModulePath; + hasteImpl = require(hasteImplModulePath); + } + let content; + let dependencies; + let id; + let module; + let sha1; + const {computeDependencies, computeSha1, rootDir, filePath} = data; + const getContent = () => { + if (content === undefined) { + content = fs().readFileSync(filePath, 'utf8'); + } + return content; + }; + if (filePath.endsWith(PACKAGE_JSON)) { + // Process a package.json that is returned as a PACKAGE type with its name. + try { + const fileData = JSON.parse(getContent()); + if (fileData.name) { + const relativeFilePath = path().relative(rootDir, filePath); + id = fileData.name; + module = [relativeFilePath, _constants.default.PACKAGE]; + } + } catch (err) { + throw new Error(`Cannot parse ${filePath} as JSON: ${err.message}`); + } + } else if ( + !_blacklist.default.has(filePath.substring(filePath.lastIndexOf('.'))) + ) { + // Process a random file that is returned as a MODULE. + if (hasteImpl) { + id = hasteImpl.getHasteName(filePath); + } + if (computeDependencies) { + const content = getContent(); + const extractor = data.dependencyExtractor + ? await (0, _jestUtil().requireOrImportModule)( + data.dependencyExtractor, + false + ) + : _dependencyExtractor.extractor; + dependencies = Array.from( + extractor.extract( + content, + filePath, + _dependencyExtractor.extractor.extract + ) + ); + } + if (id) { + const relativeFilePath = path().relative(rootDir, filePath); + module = [relativeFilePath, _constants.default.MODULE]; + } + } + + // If a SHA-1 is requested on update, compute it. + if (computeSha1) { + sha1 = sha1hex(content || fs().readFileSync(filePath)); + } + return { + dependencies, + id, + module, + sha1 + }; +} +async function getSha1(data) { + const sha1 = data.computeSha1 + ? sha1hex(fs().readFileSync(data.filePath)) + : null; + return { + dependencies: undefined, + id: undefined, + module: undefined, + sha1 + }; +} diff --git a/node_modules/jest-haste-map/package.json b/node_modules/jest-haste-map/package.json new file mode 100644 index 0000000..8b1c122 --- /dev/null +++ b/node_modules/jest-haste-map/package.json @@ -0,0 +1,48 @@ +{ + "name": "jest-haste-map", + "version": "29.2.1", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-haste-map" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/types": "^29.2.1", + "@types/graceful-fs": "^4.1.3", + "@types/node": "*", + "anymatch": "^3.0.3", + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.2.9", + "jest-regex-util": "^29.2.0", + "jest-util": "^29.2.1", + "jest-worker": "^29.2.1", + "micromatch": "^4.0.4", + "walker": "^1.0.8" + }, + "devDependencies": { + "@jest/test-utils": "^29.2.1", + "@types/fb-watchman": "^2.0.0", + "@types/micromatch": "^4.0.1", + "slash": "^3.0.0" + }, + "optionalDependencies": { + "fsevents": "^2.3.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "4551c0fdd4d25b7206824957c7bcc6baf61e63bf" +} diff --git a/node_modules/jest-leak-detector/LICENSE b/node_modules/jest-leak-detector/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-leak-detector/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-leak-detector/README.md b/node_modules/jest-leak-detector/README.md new file mode 100644 index 0000000..5e650b7 --- /dev/null +++ b/node_modules/jest-leak-detector/README.md @@ -0,0 +1,27 @@ +# jest-leak-detector + +Module for verifying whether an object has been garbage collected or not. + +Internally creates a weak reference to the object, and forces garbage collection to happen. If the reference is gone, it meant no one else was pointing to the object. + +## Example + +```javascript +(async function () { + let reference = {}; + let isLeaking; + + const detector = new LeakDetector(reference); + + // Reference is held in memory. + isLeaking = await detector.isLeaking(); + console.log(isLeaking); // true + + // We destroy the only reference to the object. + reference = null; + + // Reference is gone. + isLeaking = await detector.isLeaking(); + console.log(isLeaking); // false +})(); +``` diff --git a/node_modules/jest-leak-detector/build/index.d.ts b/node_modules/jest-leak-detector/build/index.d.ts new file mode 100644 index 0000000..0c37a9d --- /dev/null +++ b/node_modules/jest-leak-detector/build/index.d.ts @@ -0,0 +1,19 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +/// +declare class LeakDetector { + private _isReferenceBeingHeld; + private readonly _finalizationRegistry?; + constructor(value: unknown); + isLeaking(): Promise; + private _runGarbageCollector; +} +export default LeakDetector; + +export {}; diff --git a/node_modules/jest-leak-detector/build/index.js b/node_modules/jest-leak-detector/build/index.js new file mode 100644 index 0000000..d71a5c1 --- /dev/null +++ b/node_modules/jest-leak-detector/build/index.js @@ -0,0 +1,99 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _util() { + const data = require('util'); + _util = function () { + return data; + }; + return data; +} +function _v() { + const data = require('v8'); + _v = function () { + return data; + }; + return data; +} +function _vm() { + const data = require('vm'); + _vm = function () { + return data; + }; + return data; +} +function _jestGetType() { + const data = require('jest-get-type'); + _jestGetType = function () { + return data; + }; + return data; +} +function _prettyFormat() { + const data = require('pretty-format'); + _prettyFormat = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +const tick = (0, _util().promisify)(setImmediate); +class LeakDetector { + _isReferenceBeingHeld; + _finalizationRegistry; + constructor(value) { + if ((0, _jestGetType().isPrimitive)(value)) { + throw new TypeError( + [ + 'Primitives cannot leak memory.', + `You passed a ${typeof value}: <${(0, _prettyFormat().format)( + value + )}>` + ].join(' ') + ); + } + + // When `_finalizationRegistry` is GCed the callback we set will no longer be called, + this._finalizationRegistry = new FinalizationRegistry(() => { + this._isReferenceBeingHeld = false; + }); + this._finalizationRegistry.register(value, undefined); + this._isReferenceBeingHeld = true; + + // Ensure value is not leaked by the closure created by the "weak" callback. + value = null; + } + async isLeaking() { + this._runGarbageCollector(); + + // wait some ticks to allow GC to run properly, see https://github.com/nodejs/node/issues/34636#issuecomment-669366235 + for (let i = 0; i < 10; i++) { + await tick(); + } + return this._isReferenceBeingHeld; + } + _runGarbageCollector() { + // @ts-expect-error: not a function on `globalThis` + const isGarbageCollectorHidden = globalThis.gc == null; + + // GC is usually hidden, so we have to expose it before running. + (0, _v().setFlagsFromString)('--expose-gc'); + (0, _vm().runInNewContext)('gc')(); + + // The GC was not initially exposed, so let's hide it again. + if (isGarbageCollectorHidden) { + (0, _v().setFlagsFromString)('--no-expose-gc'); + } + } +} +exports.default = LeakDetector; diff --git a/node_modules/jest-leak-detector/package.json b/node_modules/jest-leak-detector/package.json new file mode 100644 index 0000000..0af555d --- /dev/null +++ b/node_modules/jest-leak-detector/package.json @@ -0,0 +1,30 @@ +{ + "name": "jest-leak-detector", + "version": "29.2.1", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-leak-detector" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "jest-get-type": "^29.2.0", + "pretty-format": "^29.2.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "4551c0fdd4d25b7206824957c7bcc6baf61e63bf" +} diff --git a/node_modules/jest-matcher-utils/LICENSE b/node_modules/jest-matcher-utils/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-matcher-utils/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-matcher-utils/README.md b/node_modules/jest-matcher-utils/README.md new file mode 100644 index 0000000..d3e9d13 --- /dev/null +++ b/node_modules/jest-matcher-utils/README.md @@ -0,0 +1,24 @@ +# jest-matcher-utils + +This package's exports are most notably used by `expect`'s [`this.utils`](https://jestjs.io/docs/expect#thisutils). + +## Installation + +To add this package as a dependency of a project, run either of the following commands: + +- `npm install jest-matcher-utils` +- `yarn add jest-matcher-utils` + +## Exports ([src/index.ts](https://github.com/facebook/jest/blob/HEAD/packages/jest-matcher-utils/src/index.ts)) + +### Functions + +`stringify` `highlightTrailingWhitespace` `printReceived` `printExpected` `printWithType` `ensureNoExpected` `ensureActualIsNumber` `ensureExpectedIsNumber` `ensureNumbers` `ensureExpectedIsNonNegativeInteger` `printDiffOrStringify` `diff` `pluralize` `getLabelPrinter` `matcherErrorMessage` `matcherHint` + +### Types + +`MatcherHintOptions` `DiffOptions` + +### Constants + +`EXPECTED_COLOR` `RECEIVED_COLOR` `INVERTED_COLOR` `BOLD_WEIGHT` `DIM_COLOR` `SUGGEST_TO_CONTAIN_EQUAL` diff --git a/node_modules/jest-matcher-utils/build/Replaceable.js b/node_modules/jest-matcher-utils/build/Replaceable.js new file mode 100644 index 0000000..8bbb4fc --- /dev/null +++ b/node_modules/jest-matcher-utils/build/Replaceable.js @@ -0,0 +1,64 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _jestGetType = require('jest-get-type'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const supportTypes = ['map', 'array', 'object']; +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +class Replaceable { + object; + type; + constructor(object) { + this.object = object; + this.type = (0, _jestGetType.getType)(object); + if (!supportTypes.includes(this.type)) { + throw new Error(`Type ${this.type} is not support in Replaceable!`); + } + } + static isReplaceable(obj1, obj2) { + const obj1Type = (0, _jestGetType.getType)(obj1); + const obj2Type = (0, _jestGetType.getType)(obj2); + return obj1Type === obj2Type && supportTypes.includes(obj1Type); + } + forEach(cb) { + if (this.type === 'object') { + const descriptors = Object.getOwnPropertyDescriptors(this.object); + [ + ...Object.keys(descriptors), + ...Object.getOwnPropertySymbols(descriptors) + ] + //@ts-expect-error because typescript do not support symbol key in object + //https://github.com/microsoft/TypeScript/issues/1863 + .filter(key => descriptors[key].enumerable) + .forEach(key => { + cb(this.object[key], key, this.object); + }); + } else { + this.object.forEach(cb); + } + } + get(key) { + if (this.type === 'map') { + return this.object.get(key); + } + return this.object[key]; + } + set(key, value) { + if (this.type === 'map') { + this.object.set(key, value); + } else { + this.object[key] = value; + } + } +} +/* eslint-enable */ +exports.default = Replaceable; diff --git a/node_modules/jest-matcher-utils/build/deepCyclicCopyReplaceable.js b/node_modules/jest-matcher-utils/build/deepCyclicCopyReplaceable.js new file mode 100644 index 0000000..e24c399 --- /dev/null +++ b/node_modules/jest-matcher-utils/build/deepCyclicCopyReplaceable.js @@ -0,0 +1,100 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = deepCyclicCopyReplaceable; +var _prettyFormat = require('pretty-format'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const builtInObject = [ + Array, + Date, + Float32Array, + Float64Array, + Int16Array, + Int32Array, + Int8Array, + Map, + Set, + RegExp, + Uint16Array, + Uint32Array, + Uint8Array, + Uint8ClampedArray +]; +if (typeof Buffer !== 'undefined') { + builtInObject.push(Buffer); +} +const isBuiltInObject = object => builtInObject.includes(object.constructor); +const isMap = value => value.constructor === Map; +function deepCyclicCopyReplaceable(value, cycles = new WeakMap()) { + if (typeof value !== 'object' || value === null) { + return value; + } else if (cycles.has(value)) { + return cycles.get(value); + } else if (Array.isArray(value)) { + return deepCyclicCopyArray(value, cycles); + } else if (isMap(value)) { + return deepCyclicCopyMap(value, cycles); + } else if (isBuiltInObject(value)) { + return value; + } else if (_prettyFormat.plugins.DOMElement.test(value)) { + return value.cloneNode(true); + } else { + return deepCyclicCopyObject(value, cycles); + } +} +function deepCyclicCopyObject(object, cycles) { + const newObject = Object.create(Object.getPrototypeOf(object)); + const descriptors = Object.getOwnPropertyDescriptors(object); + cycles.set(object, newObject); + const newDescriptors = [ + ...Object.keys(descriptors), + ...Object.getOwnPropertySymbols(descriptors) + ].reduce( + //@ts-expect-error because typescript do not support symbol key in object + //https://github.com/microsoft/TypeScript/issues/1863 + (newDescriptors, key) => { + const enumerable = descriptors[key].enumerable; + newDescriptors[key] = { + configurable: true, + enumerable, + value: deepCyclicCopyReplaceable( + // this accesses the value or getter, depending. We just care about the value anyways, and this allows us to not mess with accessors + // it has the side effect of invoking the getter here though, rather than copying it over + object[key], + cycles + ), + writable: true + }; + return newDescriptors; + }, + {} + ); + //@ts-expect-error because typescript do not support symbol key in object + //https://github.com/microsoft/TypeScript/issues/1863 + return Object.defineProperties(newObject, newDescriptors); +} +function deepCyclicCopyArray(array, cycles) { + const newArray = new (Object.getPrototypeOf(array).constructor)(array.length); + const length = array.length; + cycles.set(array, newArray); + for (let i = 0; i < length; i++) { + newArray[i] = deepCyclicCopyReplaceable(array[i], cycles); + } + return newArray; +} +function deepCyclicCopyMap(map, cycles) { + const newMap = new Map(); + cycles.set(map, newMap); + map.forEach((value, key) => { + newMap.set(key, deepCyclicCopyReplaceable(value, cycles)); + }); + return newMap; +} diff --git a/node_modules/jest-matcher-utils/build/index.d.ts b/node_modules/jest-matcher-utils/build/index.d.ts new file mode 100644 index 0000000..b000d84 --- /dev/null +++ b/node_modules/jest-matcher-utils/build/index.d.ts @@ -0,0 +1,138 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import chalk = require('chalk'); +import {DiffOptions as DiffOptions_2} from 'jest-diff'; + +export declare const BOLD_WEIGHT: chalk.Chalk; + +export declare const diff: ( + a: unknown, + b: unknown, + options?: DiffOptions, +) => string | null; + +export declare type DiffOptions = DiffOptions_2; + +export declare const DIM_COLOR: chalk.Chalk; + +/** + * Ensures that `actual` is of type `number | bigint` + */ +export declare const ensureActualIsNumber: ( + actual: unknown, + matcherName: string, + options?: MatcherHintOptions, +) => void; + +export declare const ensureExpectedIsNonNegativeInteger: ( + expected: unknown, + matcherName: string, + options?: MatcherHintOptions, +) => void; + +/** + * Ensures that `expected` is of type `number | bigint` + */ +export declare const ensureExpectedIsNumber: ( + expected: unknown, + matcherName: string, + options?: MatcherHintOptions, +) => void; + +export declare const ensureNoExpected: ( + expected: unknown, + matcherName: string, + options?: MatcherHintOptions, +) => void; + +/** + * Ensures that `actual` & `expected` are of type `number | bigint` + */ +export declare const ensureNumbers: ( + actual: unknown, + expected: unknown, + matcherName: string, + options?: MatcherHintOptions, +) => void; + +export declare const EXPECTED_COLOR: chalk.Chalk; + +export declare const getLabelPrinter: (...strings: Array) => PrintLabel; + +export declare const highlightTrailingWhitespace: (text: string) => string; + +export declare const INVERTED_COLOR: chalk.Chalk; + +export declare const matcherErrorMessage: ( + hint: string, + generic: string, + specific?: string, +) => string; + +export declare const matcherHint: ( + matcherName: string, + received?: string, + expected?: string, + options?: MatcherHintOptions, +) => string; + +declare type MatcherHintColor = (arg: string) => string; + +export declare type MatcherHintOptions = { + comment?: string; + expectedColor?: MatcherHintColor; + isDirectExpectCall?: boolean; + isNot?: boolean; + promise?: string; + receivedColor?: MatcherHintColor; + secondArgument?: string; + secondArgumentColor?: MatcherHintColor; +}; + +export declare const pluralize: (word: string, count: number) => string; + +export declare const printDiffOrStringify: ( + expected: unknown, + received: unknown, + expectedLabel: string, + receivedLabel: string, + expand: boolean, +) => string; + +export declare const printExpected: (value: unknown) => string; + +declare type PrintLabel = (string: string) => string; + +export declare const printReceived: (object: unknown) => string; + +export declare function printWithType( + name: string, + value: T, + print: (value: T) => string, +): string; + +export declare const RECEIVED_COLOR: chalk.Chalk; + +export declare function replaceMatchedToAsymmetricMatcher( + replacedExpected: unknown, + replacedReceived: unknown, + expectedCycles: Array, + receivedCycles: Array, +): { + replacedExpected: unknown; + replacedReceived: unknown; +}; + +export declare const stringify: ( + object: unknown, + maxDepth?: number, + maxWidth?: number, +) => string; + +export declare const SUGGEST_TO_CONTAIN_EQUAL: string; + +export {}; diff --git a/node_modules/jest-matcher-utils/build/index.js b/node_modules/jest-matcher-utils/build/index.js new file mode 100644 index 0000000..a7bea63 --- /dev/null +++ b/node_modules/jest-matcher-utils/build/index.js @@ -0,0 +1,539 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printReceived = + exports.printExpected = + exports.printDiffOrStringify = + exports.pluralize = + exports.matcherHint = + exports.matcherErrorMessage = + exports.highlightTrailingWhitespace = + exports.getLabelPrinter = + exports.ensureNumbers = + exports.ensureNoExpected = + exports.ensureExpectedIsNumber = + exports.ensureExpectedIsNonNegativeInteger = + exports.ensureActualIsNumber = + exports.diff = + exports.SUGGEST_TO_CONTAIN_EQUAL = + exports.RECEIVED_COLOR = + exports.INVERTED_COLOR = + exports.EXPECTED_COLOR = + exports.DIM_COLOR = + exports.BOLD_WEIGHT = + void 0; +exports.printWithType = printWithType; +exports.replaceMatchedToAsymmetricMatcher = replaceMatchedToAsymmetricMatcher; +exports.stringify = void 0; +var _chalk = _interopRequireDefault(require('chalk')); +var _jestDiff = require('jest-diff'); +var _jestGetType = require('jest-get-type'); +var _prettyFormat = require('pretty-format'); +var _Replaceable = _interopRequireDefault(require('./Replaceable')); +var _deepCyclicCopyReplaceable = _interopRequireDefault( + require('./deepCyclicCopyReplaceable') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/ban-types-eventually */ + +const { + AsymmetricMatcher, + DOMCollection, + DOMElement, + Immutable, + ReactElement, + ReactTestComponent +} = _prettyFormat.plugins; +const PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + AsymmetricMatcher +]; +const EXPECTED_COLOR = _chalk.default.green; +exports.EXPECTED_COLOR = EXPECTED_COLOR; +const RECEIVED_COLOR = _chalk.default.red; +exports.RECEIVED_COLOR = RECEIVED_COLOR; +const INVERTED_COLOR = _chalk.default.inverse; +exports.INVERTED_COLOR = INVERTED_COLOR; +const BOLD_WEIGHT = _chalk.default.bold; +exports.BOLD_WEIGHT = BOLD_WEIGHT; +const DIM_COLOR = _chalk.default.dim; +exports.DIM_COLOR = DIM_COLOR; +const MULTILINE_REGEXP = /\n/; +const SPACE_SYMBOL = '\u{00B7}'; // middle dot + +const NUMBERS = [ + 'zero', + 'one', + 'two', + 'three', + 'four', + 'five', + 'six', + 'seven', + 'eight', + 'nine', + 'ten', + 'eleven', + 'twelve', + 'thirteen' +]; +const SUGGEST_TO_CONTAIN_EQUAL = _chalk.default.dim( + 'Looks like you wanted to test for object/array equality with the stricter `toContain` matcher. You probably need to use `toContainEqual` instead.' +); +exports.SUGGEST_TO_CONTAIN_EQUAL = SUGGEST_TO_CONTAIN_EQUAL; +const stringify = (object, maxDepth = 10, maxWidth = 10) => { + const MAX_LENGTH = 10000; + let result; + try { + result = (0, _prettyFormat.format)(object, { + maxDepth, + maxWidth, + min: true, + plugins: PLUGINS + }); + } catch { + result = (0, _prettyFormat.format)(object, { + callToJSON: false, + maxDepth, + maxWidth, + min: true, + plugins: PLUGINS + }); + } + if (result.length >= MAX_LENGTH && maxDepth > 1) { + return stringify(object, Math.floor(maxDepth / 2), maxWidth); + } else if (result.length >= MAX_LENGTH && maxWidth > 1) { + return stringify(object, maxDepth, Math.floor(maxWidth / 2)); + } else { + return result; + } +}; +exports.stringify = stringify; +const highlightTrailingWhitespace = text => + text.replace(/\s+$/gm, _chalk.default.inverse('$&')); + +// Instead of inverse highlight which now implies a change, +// replace common spaces with middle dot at the end of any line. +exports.highlightTrailingWhitespace = highlightTrailingWhitespace; +const replaceTrailingSpaces = text => + text.replace(/\s+$/gm, spaces => SPACE_SYMBOL.repeat(spaces.length)); +const printReceived = object => + RECEIVED_COLOR(replaceTrailingSpaces(stringify(object))); +exports.printReceived = printReceived; +const printExpected = value => + EXPECTED_COLOR(replaceTrailingSpaces(stringify(value))); +exports.printExpected = printExpected; +function printWithType(name, value, print) { + const type = (0, _jestGetType.getType)(value); + const hasType = + type !== 'null' && type !== 'undefined' + ? `${name} has type: ${type}\n` + : ''; + const hasValue = `${name} has value: ${print(value)}`; + return hasType + hasValue; +} +const ensureNoExpected = (expected, matcherName, options) => { + if (typeof expected !== 'undefined') { + // Prepend maybe not only for backward compatibility. + const matcherString = (options ? '' : '[.not]') + matcherName; + throw new Error( + matcherErrorMessage( + matcherHint(matcherString, undefined, '', options), + // Because expected is omitted in hint above, + // expected is black instead of green in message below. + 'this matcher must not have an expected argument', + printWithType('Expected', expected, printExpected) + ) + ); + } +}; + +/** + * Ensures that `actual` is of type `number | bigint` + */ +exports.ensureNoExpected = ensureNoExpected; +const ensureActualIsNumber = (actual, matcherName, options) => { + if (typeof actual !== 'number' && typeof actual !== 'bigint') { + // Prepend maybe not only for backward compatibility. + const matcherString = (options ? '' : '[.not]') + matcherName; + throw new Error( + matcherErrorMessage( + matcherHint(matcherString, undefined, undefined, options), + `${RECEIVED_COLOR('received')} value must be a number or bigint`, + printWithType('Received', actual, printReceived) + ) + ); + } +}; + +/** + * Ensures that `expected` is of type `number | bigint` + */ +exports.ensureActualIsNumber = ensureActualIsNumber; +const ensureExpectedIsNumber = (expected, matcherName, options) => { + if (typeof expected !== 'number' && typeof expected !== 'bigint') { + // Prepend maybe not only for backward compatibility. + const matcherString = (options ? '' : '[.not]') + matcherName; + throw new Error( + matcherErrorMessage( + matcherHint(matcherString, undefined, undefined, options), + `${EXPECTED_COLOR('expected')} value must be a number or bigint`, + printWithType('Expected', expected, printExpected) + ) + ); + } +}; + +/** + * Ensures that `actual` & `expected` are of type `number | bigint` + */ +exports.ensureExpectedIsNumber = ensureExpectedIsNumber; +const ensureNumbers = (actual, expected, matcherName, options) => { + ensureActualIsNumber(actual, matcherName, options); + ensureExpectedIsNumber(expected, matcherName, options); +}; +exports.ensureNumbers = ensureNumbers; +const ensureExpectedIsNonNegativeInteger = (expected, matcherName, options) => { + if ( + typeof expected !== 'number' || + !Number.isSafeInteger(expected) || + expected < 0 + ) { + // Prepend maybe not only for backward compatibility. + const matcherString = (options ? '' : '[.not]') + matcherName; + throw new Error( + matcherErrorMessage( + matcherHint(matcherString, undefined, undefined, options), + `${EXPECTED_COLOR('expected')} value must be a non-negative integer`, + printWithType('Expected', expected, printExpected) + ) + ); + } +}; + +// Given array of diffs, return concatenated string: +// * include common substrings +// * exclude change substrings which have opposite op +// * include change substrings which have argument op +// with inverse highlight only if there is a common substring +exports.ensureExpectedIsNonNegativeInteger = ensureExpectedIsNonNegativeInteger; +const getCommonAndChangedSubstrings = (diffs, op, hasCommonDiff) => + diffs.reduce( + (reduced, diff) => + reduced + + (diff[0] === _jestDiff.DIFF_EQUAL + ? diff[1] + : diff[0] !== op + ? '' + : hasCommonDiff + ? INVERTED_COLOR(diff[1]) + : diff[1]), + '' + ); +const isLineDiffable = (expected, received) => { + const expectedType = (0, _jestGetType.getType)(expected); + const receivedType = (0, _jestGetType.getType)(received); + if (expectedType !== receivedType) { + return false; + } + if ((0, _jestGetType.isPrimitive)(expected)) { + // Print generic line diff for strings only: + // * if neither string is empty + // * if either string has more than one line + return ( + typeof expected === 'string' && + typeof received === 'string' && + expected.length !== 0 && + received.length !== 0 && + (MULTILINE_REGEXP.test(expected) || MULTILINE_REGEXP.test(received)) + ); + } + if ( + expectedType === 'date' || + expectedType === 'function' || + expectedType === 'regexp' + ) { + return false; + } + if (expected instanceof Error && received instanceof Error) { + return false; + } + if ( + receivedType === 'object' && + typeof received.asymmetricMatch === 'function' + ) { + return false; + } + return true; +}; +const MAX_DIFF_STRING_LENGTH = 20000; +const printDiffOrStringify = ( + expected, + received, + expectedLabel, + receivedLabel, + expand // CLI options: true if `--expand` or false if `--no-expand` +) => { + if ( + typeof expected === 'string' && + typeof received === 'string' && + expected.length !== 0 && + received.length !== 0 && + expected.length <= MAX_DIFF_STRING_LENGTH && + received.length <= MAX_DIFF_STRING_LENGTH && + expected !== received + ) { + if (expected.includes('\n') || received.includes('\n')) { + return (0, _jestDiff.diffStringsUnified)(expected, received, { + aAnnotation: expectedLabel, + bAnnotation: receivedLabel, + changeLineTrailingSpaceColor: _chalk.default.bgYellow, + commonLineTrailingSpaceColor: _chalk.default.bgYellow, + emptyFirstOrLastLinePlaceholder: '↵', + // U+21B5 + expand, + includeChangeCounts: true + }); + } + const diffs = (0, _jestDiff.diffStringsRaw)(expected, received, true); + const hasCommonDiff = diffs.some(diff => diff[0] === _jestDiff.DIFF_EQUAL); + const printLabel = getLabelPrinter(expectedLabel, receivedLabel); + const expectedLine = + printLabel(expectedLabel) + + printExpected( + getCommonAndChangedSubstrings( + diffs, + _jestDiff.DIFF_DELETE, + hasCommonDiff + ) + ); + const receivedLine = + printLabel(receivedLabel) + + printReceived( + getCommonAndChangedSubstrings( + diffs, + _jestDiff.DIFF_INSERT, + hasCommonDiff + ) + ); + return `${expectedLine}\n${receivedLine}`; + } + if (isLineDiffable(expected, received)) { + const {replacedExpected, replacedReceived} = + replaceMatchedToAsymmetricMatcher(expected, received, [], []); + const difference = (0, _jestDiff.diff)(replacedExpected, replacedReceived, { + aAnnotation: expectedLabel, + bAnnotation: receivedLabel, + expand, + includeChangeCounts: true + }); + if ( + typeof difference === 'string' && + difference.includes(`- ${expectedLabel}`) && + difference.includes(`+ ${receivedLabel}`) + ) { + return difference; + } + } + const printLabel = getLabelPrinter(expectedLabel, receivedLabel); + const expectedLine = printLabel(expectedLabel) + printExpected(expected); + const receivedLine = + printLabel(receivedLabel) + + (stringify(expected) === stringify(received) + ? 'serializes to the same string' + : printReceived(received)); + return `${expectedLine}\n${receivedLine}`; +}; + +// Sometimes, e.g. when comparing two numbers, the output from jest-diff +// does not contain more information than the `Expected:` / `Received:` already gives. +// In those cases, we do not print a diff to make the output shorter and not redundant. +exports.printDiffOrStringify = printDiffOrStringify; +const shouldPrintDiff = (actual, expected) => { + if (typeof actual === 'number' && typeof expected === 'number') { + return false; + } + if (typeof actual === 'bigint' && typeof expected === 'bigint') { + return false; + } + if (typeof actual === 'boolean' && typeof expected === 'boolean') { + return false; + } + return true; +}; +function replaceMatchedToAsymmetricMatcher( + replacedExpected, + replacedReceived, + expectedCycles, + receivedCycles +) { + return _replaceMatchedToAsymmetricMatcher( + (0, _deepCyclicCopyReplaceable.default)(replacedExpected), + (0, _deepCyclicCopyReplaceable.default)(replacedReceived), + expectedCycles, + receivedCycles + ); +} +function _replaceMatchedToAsymmetricMatcher( + replacedExpected, + replacedReceived, + expectedCycles, + receivedCycles +) { + if (!_Replaceable.default.isReplaceable(replacedExpected, replacedReceived)) { + return { + replacedExpected, + replacedReceived + }; + } + if ( + expectedCycles.includes(replacedExpected) || + receivedCycles.includes(replacedReceived) + ) { + return { + replacedExpected, + replacedReceived + }; + } + expectedCycles.push(replacedExpected); + receivedCycles.push(replacedReceived); + const expectedReplaceable = new _Replaceable.default(replacedExpected); + const receivedReplaceable = new _Replaceable.default(replacedReceived); + expectedReplaceable.forEach((expectedValue, key) => { + const receivedValue = receivedReplaceable.get(key); + if (isAsymmetricMatcher(expectedValue)) { + if (expectedValue.asymmetricMatch(receivedValue)) { + receivedReplaceable.set(key, expectedValue); + } + } else if (isAsymmetricMatcher(receivedValue)) { + if (receivedValue.asymmetricMatch(expectedValue)) { + expectedReplaceable.set(key, receivedValue); + } + } else if ( + _Replaceable.default.isReplaceable(expectedValue, receivedValue) + ) { + const replaced = _replaceMatchedToAsymmetricMatcher( + expectedValue, + receivedValue, + expectedCycles, + receivedCycles + ); + expectedReplaceable.set(key, replaced.replacedExpected); + receivedReplaceable.set(key, replaced.replacedReceived); + } + }); + return { + replacedExpected: expectedReplaceable.object, + replacedReceived: receivedReplaceable.object + }; +} +function isAsymmetricMatcher(data) { + const type = (0, _jestGetType.getType)(data); + return type === 'object' && typeof data.asymmetricMatch === 'function'; +} +const diff = (a, b, options) => + shouldPrintDiff(a, b) ? (0, _jestDiff.diff)(a, b, options) : null; +exports.diff = diff; +const pluralize = (word, count) => + `${NUMBERS[count] || count} ${word}${count === 1 ? '' : 's'}`; + +// To display lines of labeled values as two columns with monospace alignment: +// given the strings which will describe the values, +// return function which given each string, returns the label: +// string, colon, space, and enough padding spaces to align the value. +exports.pluralize = pluralize; +const getLabelPrinter = (...strings) => { + const maxLength = strings.reduce( + (max, string) => (string.length > max ? string.length : max), + 0 + ); + return string => `${string}: ${' '.repeat(maxLength - string.length)}`; +}; +exports.getLabelPrinter = getLabelPrinter; +const matcherErrorMessage = ( + hint, + generic, + specific // incorrect value returned from call to printWithType +) => + `${hint}\n\n${_chalk.default.bold('Matcher error')}: ${generic}${ + typeof specific === 'string' ? `\n\n${specific}` : '' + }`; + +// Display assertion for the report when a test fails. +// New format: rejects/resolves, not, and matcher name have black color +// Old format: matcher name has dim color +exports.matcherErrorMessage = matcherErrorMessage; +const matcherHint = ( + matcherName, + received = 'received', + expected = 'expected', + options = {} +) => { + const { + comment = '', + expectedColor = EXPECTED_COLOR, + isDirectExpectCall = false, + // seems redundant with received === '' + isNot = false, + promise = '', + receivedColor = RECEIVED_COLOR, + secondArgument = '', + secondArgumentColor = EXPECTED_COLOR + } = options; + let hint = ''; + let dimString = 'expect'; // concatenate adjacent dim substrings + + if (!isDirectExpectCall && received !== '') { + hint += DIM_COLOR(`${dimString}(`) + receivedColor(received); + dimString = ')'; + } + if (promise !== '') { + hint += DIM_COLOR(`${dimString}.`) + promise; + dimString = ''; + } + if (isNot) { + hint += `${DIM_COLOR(`${dimString}.`)}not`; + dimString = ''; + } + if (matcherName.includes('.')) { + // Old format: for backward compatibility, + // especially without promise or isNot options + dimString += matcherName; + } else { + // New format: omit period from matcherName arg + hint += DIM_COLOR(`${dimString}.`) + matcherName; + dimString = ''; + } + if (expected === '') { + dimString += '()'; + } else { + hint += DIM_COLOR(`${dimString}(`) + expectedColor(expected); + if (secondArgument) { + hint += DIM_COLOR(', ') + secondArgumentColor(secondArgument); + } + dimString = ')'; + } + if (comment !== '') { + dimString += ` // ${comment}`; + } + if (dimString !== '') { + hint += DIM_COLOR(dimString); + } + return hint; +}; +exports.matcherHint = matcherHint; diff --git a/node_modules/jest-matcher-utils/package.json b/node_modules/jest-matcher-utils/package.json new file mode 100644 index 0000000..d20b21e --- /dev/null +++ b/node_modules/jest-matcher-utils/package.json @@ -0,0 +1,37 @@ +{ + "name": "jest-matcher-utils", + "description": "A set of utility functions for expect and related packages", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-matcher-utils" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "chalk": "^4.0.0", + "jest-diff": "^29.2.1", + "jest-get-type": "^29.2.0", + "pretty-format": "^29.2.1" + }, + "devDependencies": { + "@jest/test-utils": "^29.2.1", + "@types/node": "*" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-message-util/LICENSE b/node_modules/jest-message-util/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-message-util/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-message-util/build/index.d.ts b/node_modules/jest-message-util/build/index.d.ts new file mode 100644 index 0000000..b069c55 --- /dev/null +++ b/node_modules/jest-message-util/build/index.d.ts @@ -0,0 +1,67 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config} from '@jest/types'; +import type {StackData} from 'stack-utils'; +import type {TestResult} from '@jest/types'; + +export declare const formatExecError: ( + error: Error | TestResult.SerializableError | string | undefined, + config: StackTraceConfig, + options: StackTraceOptions, + testPath?: string, + reuseMessage?: boolean, +) => string; + +export declare const formatPath: ( + line: string, + config: StackTraceConfig, + relativeTestPath?: string | null, +) => string; + +export declare const formatResultsErrors: ( + testResults: Array, + config: StackTraceConfig, + options: StackTraceOptions, + testPath?: string, +) => string | null; + +export declare const formatStackTrace: ( + stack: string, + config: StackTraceConfig, + options: StackTraceOptions, + testPath?: string, +) => string; + +export declare interface Frame extends StackData { + file: string; +} + +export declare const getStackTraceLines: ( + stack: string, + options?: StackTraceOptions, +) => Array; + +export declare const getTopFrame: (lines: Array) => Frame | null; + +export declare const indentAllLines: (lines: string) => string; + +export declare const separateMessageFromStack: (content: string) => { + message: string; + stack: string; +}; + +export declare type StackTraceConfig = Pick< + Config.ProjectConfig, + 'rootDir' | 'testMatch' +>; + +export declare type StackTraceOptions = { + noStackTrace: boolean; + noCodeFrame?: boolean; +}; + +export {}; diff --git a/node_modules/jest-message-util/build/index.js b/node_modules/jest-message-util/build/index.js new file mode 100644 index 0000000..e23efee --- /dev/null +++ b/node_modules/jest-message-util/build/index.js @@ -0,0 +1,395 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.separateMessageFromStack = + exports.indentAllLines = + exports.getTopFrame = + exports.getStackTraceLines = + exports.formatStackTrace = + exports.formatResultsErrors = + exports.formatPath = + exports.formatExecError = + void 0; +var path = _interopRequireWildcard(require('path')); +var _url = require('url'); +var _codeFrame = require('@babel/code-frame'); +var _chalk = _interopRequireDefault(require('chalk')); +var fs = _interopRequireWildcard(require('graceful-fs')); +var _micromatch = _interopRequireDefault(require('micromatch')); +var _slash = _interopRequireDefault(require('slash')); +var _stackUtils = _interopRequireDefault(require('stack-utils')); +var _prettyFormat = require('pretty-format'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestReadFile = + globalThis[Symbol.for('jest-native-read-file')] || fs.readFileSync; +// stack utils tries to create pretty stack by making paths relative. +const stackUtils = new _stackUtils.default({ + cwd: 'something which does not exist' +}); +let nodeInternals = []; +try { + nodeInternals = _stackUtils.default.nodeInternals(); +} catch { + // `StackUtils.nodeInternals()` fails in browsers. We don't need to remove + // node internals in the browser though, so no issue. +} +const PATH_NODE_MODULES = `${path.sep}node_modules${path.sep}`; +const PATH_JEST_PACKAGES = `${path.sep}jest${path.sep}packages${path.sep}`; + +// filter for noisy stack trace lines +const JASMINE_IGNORE = + /^\s+at(?:(?:.jasmine-)|\s+jasmine\.buildExpectationResult)/; +const JEST_INTERNALS_IGNORE = + /^\s+at.*?jest(-.*?)?(\/|\\)(build|node_modules|packages)(\/|\\)/; +const ANONYMOUS_FN_IGNORE = /^\s+at .*$/; +const ANONYMOUS_PROMISE_IGNORE = /^\s+at (new )?Promise \(\).*$/; +const ANONYMOUS_GENERATOR_IGNORE = /^\s+at Generator.next \(\).*$/; +const NATIVE_NEXT_IGNORE = /^\s+at next \(native\).*$/; +const TITLE_INDENT = ' '; +const MESSAGE_INDENT = ' '; +const STACK_INDENT = ' '; +const ANCESTRY_SEPARATOR = ' \u203A '; +const TITLE_BULLET = _chalk.default.bold('\u25cf '); +const STACK_TRACE_COLOR = _chalk.default.dim; +const STACK_PATH_REGEXP = /\s*at.*\(?(:\d*:\d*|native)\)?/; +const EXEC_ERROR_MESSAGE = 'Test suite failed to run'; +const NOT_EMPTY_LINE_REGEXP = /^(?!$)/gm; +const indentAllLines = lines => + lines.replace(NOT_EMPTY_LINE_REGEXP, MESSAGE_INDENT); +exports.indentAllLines = indentAllLines; +const trim = string => (string || '').trim(); + +// Some errors contain not only line numbers in stack traces +// e.g. SyntaxErrors can contain snippets of code, and we don't +// want to trim those, because they may have pointers to the column/character +// which will get misaligned. +const trimPaths = string => + string.match(STACK_PATH_REGEXP) ? trim(string) : string; +const getRenderedCallsite = (fileContent, line, column) => { + let renderedCallsite = (0, _codeFrame.codeFrameColumns)( + fileContent, + { + start: { + column, + line + } + }, + { + highlightCode: true + } + ); + renderedCallsite = indentAllLines(renderedCallsite); + renderedCallsite = `\n${renderedCallsite}\n`; + return renderedCallsite; +}; +const blankStringRegexp = /^\s*$/; +function checkForCommonEnvironmentErrors(error) { + if ( + error.includes('ReferenceError: document is not defined') || + error.includes('ReferenceError: window is not defined') || + error.includes('ReferenceError: navigator is not defined') + ) { + return warnAboutWrongTestEnvironment(error, 'jsdom'); + } else if (error.includes('.unref is not a function')) { + return warnAboutWrongTestEnvironment(error, 'node'); + } + return error; +} +function warnAboutWrongTestEnvironment(error, env) { + return ( + _chalk.default.bold.red( + `The error below may be caused by using the wrong test environment, see ${_chalk.default.dim.underline( + 'https://jestjs.io/docs/configuration#testenvironment-string' + )}.\nConsider using the "${env}" test environment.\n\n` + ) + error + ); +} + +// ExecError is an error thrown outside of the test suite (not inside an `it` or +// `before/after each` hooks). If it's thrown, none of the tests in the file +// are executed. +const formatExecError = (error, config, options, testPath, reuseMessage) => { + if (!error || typeof error === 'number') { + error = new Error(`Expected an Error, but "${String(error)}" was thrown`); + error.stack = ''; + } + let message, stack; + if (typeof error === 'string' || !error) { + error || (error = 'EMPTY ERROR'); + message = ''; + stack = error; + } else { + message = error.message; + stack = + typeof error.stack === 'string' + ? error.stack + : `thrown: ${(0, _prettyFormat.format)(error, { + maxDepth: 3 + })}`; + } + const separated = separateMessageFromStack(stack || ''); + stack = separated.stack; + if (separated.message.includes(trim(message))) { + // Often stack trace already contains the duplicate of the message + message = separated.message; + } + message = checkForCommonEnvironmentErrors(message); + message = indentAllLines(message); + stack = + stack && !options.noStackTrace + ? `\n${formatStackTrace(stack, config, options, testPath)}` + : ''; + if ( + typeof stack !== 'string' || + (blankStringRegexp.test(message) && blankStringRegexp.test(stack)) + ) { + // this can happen if an empty object is thrown. + message = `thrown: ${(0, _prettyFormat.format)(error, { + maxDepth: 3 + })}`; + } + let messageToUse; + if (reuseMessage) { + messageToUse = ` ${message.trim()}`; + } else { + messageToUse = `${EXEC_ERROR_MESSAGE}\n\n${message}`; + } + return `${TITLE_INDENT + TITLE_BULLET + messageToUse + stack}\n`; +}; +exports.formatExecError = formatExecError; +const removeInternalStackEntries = (lines, options) => { + let pathCounter = 0; + return lines.filter(line => { + if (ANONYMOUS_FN_IGNORE.test(line)) { + return false; + } + if (ANONYMOUS_PROMISE_IGNORE.test(line)) { + return false; + } + if (ANONYMOUS_GENERATOR_IGNORE.test(line)) { + return false; + } + if (NATIVE_NEXT_IGNORE.test(line)) { + return false; + } + if (nodeInternals.some(internal => internal.test(line))) { + return false; + } + if (!STACK_PATH_REGEXP.test(line)) { + return true; + } + if (JASMINE_IGNORE.test(line)) { + return false; + } + if (++pathCounter === 1) { + return true; // always keep the first line even if it's from Jest + } + + if (options.noStackTrace) { + return false; + } + if (JEST_INTERNALS_IGNORE.test(line)) { + return false; + } + return true; + }); +}; +const formatPath = (line, config, relativeTestPath = null) => { + // Extract the file path from the trace line. + const match = line.match(/(^\s*at .*?\(?)([^()]+)(:[0-9]+:[0-9]+\)?.*$)/); + if (!match) { + return line; + } + let filePath = (0, _slash.default)(path.relative(config.rootDir, match[2])); + // highlight paths from the current test file + if ( + (config.testMatch && + config.testMatch.length && + (0, _micromatch.default)([filePath], config.testMatch).length > 0) || + filePath === relativeTestPath + ) { + filePath = _chalk.default.reset.cyan(filePath); + } + return STACK_TRACE_COLOR(match[1]) + filePath + STACK_TRACE_COLOR(match[3]); +}; +exports.formatPath = formatPath; +const getStackTraceLines = ( + stack, + options = { + noCodeFrame: false, + noStackTrace: false + } +) => removeInternalStackEntries(stack.split(/\n/), options); +exports.getStackTraceLines = getStackTraceLines; +const getTopFrame = lines => { + for (const line of lines) { + if (line.includes(PATH_NODE_MODULES) || line.includes(PATH_JEST_PACKAGES)) { + continue; + } + const parsedFrame = stackUtils.parseLine(line.trim()); + if (parsedFrame && parsedFrame.file) { + if (parsedFrame.file.startsWith('file://')) { + parsedFrame.file = (0, _slash.default)( + (0, _url.fileURLToPath)(parsedFrame.file) + ); + } + return parsedFrame; + } + } + return null; +}; +exports.getTopFrame = getTopFrame; +const formatStackTrace = (stack, config, options, testPath) => { + const lines = getStackTraceLines(stack, options); + let renderedCallsite = ''; + const relativeTestPath = testPath + ? (0, _slash.default)(path.relative(config.rootDir, testPath)) + : null; + if (!options.noStackTrace && !options.noCodeFrame) { + const topFrame = getTopFrame(lines); + if (topFrame) { + const {column, file: filename, line} = topFrame; + if (line && filename && path.isAbsolute(filename)) { + let fileContent; + try { + // TODO: check & read HasteFS instead of reading the filesystem: + // see: https://github.com/facebook/jest/pull/5405#discussion_r164281696 + fileContent = jestReadFile(filename, 'utf8'); + renderedCallsite = getRenderedCallsite(fileContent, line, column); + } catch { + // the file does not exist or is inaccessible, we ignore + } + } + } + } + const stacktrace = lines + .filter(Boolean) + .map( + line => + STACK_INDENT + formatPath(trimPaths(line), config, relativeTestPath) + ) + .join('\n'); + return renderedCallsite + ? `${renderedCallsite}\n${stacktrace}` + : `\n${stacktrace}`; +}; +exports.formatStackTrace = formatStackTrace; +const formatResultsErrors = (testResults, config, options, testPath) => { + const failedResults = testResults.reduce((errors, result) => { + result.failureMessages.forEach(item => { + errors.push({ + content: checkForCommonEnvironmentErrors(item), + result + }); + }); + return errors; + }, []); + if (!failedResults.length) { + return null; + } + return failedResults + .map(({result, content}) => { + let {message, stack} = separateMessageFromStack(content); + stack = options.noStackTrace + ? '' + : `${STACK_TRACE_COLOR( + formatStackTrace(stack, config, options, testPath) + )}\n`; + message = indentAllLines(message); + const title = `${_chalk.default.bold.red( + TITLE_INDENT + + TITLE_BULLET + + result.ancestorTitles.join(ANCESTRY_SEPARATOR) + + (result.ancestorTitles.length ? ANCESTRY_SEPARATOR : '') + + result.title + )}\n`; + return `${title}\n${message}\n${stack}`; + }) + .join('\n'); +}; +exports.formatResultsErrors = formatResultsErrors; +const errorRegexp = /^Error:?\s*$/; +const removeBlankErrorLine = str => + str + .split('\n') + // Lines saying just `Error:` are useless + .filter(line => !errorRegexp.test(line)) + .join('\n') + .trimRight(); + +// jasmine and worker farm sometimes don't give us access to the actual +// Error object, so we have to regexp out the message from the stack string +// to format it. +const separateMessageFromStack = content => { + if (!content) { + return { + message: '', + stack: '' + }; + } + + // All lines up to what looks like a stack -- or if nothing looks like a stack + // (maybe it's a code frame instead), just the first non-empty line. + // If the error is a plain "Error:" instead of a SyntaxError or TypeError we + // remove the prefix from the message because it is generally not useful. + const messageMatch = content.match( + /^(?:Error: )?([\s\S]*?(?=\n\s*at\s.*:\d*:\d*)|\s*.*)([\s\S]*)$/ + ); + if (!messageMatch) { + // For typescript + throw new Error('If you hit this error, the regex above is buggy.'); + } + const message = removeBlankErrorLine(messageMatch[1]); + const stack = removeBlankErrorLine(messageMatch[2]); + return { + message, + stack + }; +}; +exports.separateMessageFromStack = separateMessageFromStack; diff --git a/node_modules/jest-message-util/build/types.js b/node_modules/jest-message-util/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-message-util/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-message-util/package.json b/node_modules/jest-message-util/package.json new file mode 100644 index 0000000..472d11c --- /dev/null +++ b/node_modules/jest-message-util/package.json @@ -0,0 +1,42 @@ +{ + "name": "jest-message-util", + "version": "29.2.1", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-message-util" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@babel/code-frame": "^7.12.13", + "@jest/types": "^29.2.1", + "@types/stack-utils": "^2.0.0", + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "micromatch": "^4.0.4", + "pretty-format": "^29.2.1", + "slash": "^3.0.0", + "stack-utils": "^2.0.3" + }, + "devDependencies": { + "@types/babel__code-frame": "^7.0.0", + "@types/graceful-fs": "^4.1.3", + "@types/micromatch": "^4.0.1" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "4551c0fdd4d25b7206824957c7bcc6baf61e63bf" +} diff --git a/node_modules/jest-mock/LICENSE b/node_modules/jest-mock/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-mock/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-mock/README.md b/node_modules/jest-mock/README.md new file mode 100644 index 0000000..41588a0 --- /dev/null +++ b/node_modules/jest-mock/README.md @@ -0,0 +1,106 @@ +# jest-mock + +**Note:** More details on user side API can be found in [Jest documentation](https://jestjs.io/docs/mock-function-api). + +## API + +```js +import {ModuleMocker} from 'jest-mock'; +``` + +### `constructor(global)` + +Creates a new module mocker that generates mocks as if they were created in an environment with the given global object. + +### `generateFromMetadata(metadata)` + +Generates a mock based on the given metadata (Metadata for the mock in the schema returned by the `getMetadata()` method of this module). Mocks treat functions specially, and all mock functions have additional members, described in the documentation for `fn()` in this module. + +One important note: function prototypes are handled specially by this mocking framework. For functions with prototypes, when called as a constructor, the mock will install mocked function members on the instance. This allows different instances of the same constructor to have different values for its mocks member and its return values. + +### `getMetadata(component)` + +Inspects the argument and returns its schema in the following recursive format: + +``` +{ + type: ... + members: {} +} +``` + +Where type is one of `array`, `object`, `function`, or `ref`, and members is an optional dictionary where the keys are member names and the values are metadata objects. Function prototypes are defined by defining metadata for the `member.prototype` of the function. The type of a function prototype should always be `object`. For instance, a class might be defined like this: + +```js +const classDef = { + type: 'function', + members: { + staticMethod: {type: 'function'}, + prototype: { + type: 'object', + members: { + instanceMethod: {type: 'function'}, + }, + }, + }, +}; +``` + +Metadata may also contain references to other objects defined within the same metadata object. The metadata for the referent must be marked with `refID` key and an arbitrary value. The referrer must be marked with a `ref` key that has the same value as object with refID that it refers to. For instance, this metadata blob: + +```js +const refID = { + type: 'object', + refID: 1, + members: { + self: {ref: 1}, + }, +}; +``` + +Defines an object with a slot named `self` that refers back to the object. + +### `fn(implementation?)` + +Generates a stand-alone function with members that help drive unit tests or confirm expectations. Specifically, functions returned by this method have the following members: + +##### `.mock` + +An object with three members, `calls`, `instances` and `invocationCallOrder`, which are all lists. The items in the `calls` list are the arguments with which the function was called. The "instances" list stores the value of 'this' for each call to the function. This is useful for retrieving instances from a constructor. The `invocationCallOrder` lists the order in which the mock was called in relation to all mock calls, starting at 1. + +##### `.mockReturnValueOnce(value)` + +Pushes the given value onto a FIFO queue of return values for the function. + +##### `.mockReturnValue(value)` + +Sets the default return value for the function. + +##### `.mockImplementationOnce(function)` + +Pushes the given mock implementation onto a FIFO queue of mock implementations for the function. + +##### `.mockImplementation(function)` + +Sets the default mock implementation for the function. + +##### `.mockReturnThis()` + +Syntactic sugar for: + +```js +mockFn.mockImplementation(function () { + return this; +}); +``` + +In case both `.mockImplementationOnce()` / `.mockImplementation()` and `.mockReturnValueOnce()` / `.mockReturnValue()` are called. The priority of which to use is based on what is the last call: + +- if the last call is `.mockReturnValueOnce()` or `.mockReturnValue()`, use the specific return value or default return value. If specific return values are used up or no default return value is set, fall back to try `.mockImplementation()`; +- if the last call is `.mockImplementationOnce()` or `.mockImplementation()`, run the specific implementation and return the result or run default implementation and return the result. + +##### `.withImplementation(function, callback)` + +Temporarily overrides the default mock implementation within the callback, then restores it's previous implementation. + +If the callback is async or returns a `thenable`, `withImplementation` will return a promise. Awaiting the promise will await the callback and reset the implementation. diff --git a/node_modules/jest-mock/build/index.d.ts b/node_modules/jest-mock/build/index.d.ts new file mode 100644 index 0000000..ac8c857 --- /dev/null +++ b/node_modules/jest-mock/build/index.d.ts @@ -0,0 +1,380 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +export declare type ClassLike = { + new (...args: any): any; +}; + +export declare type ConstructorLikeKeys = keyof { + [K in keyof T as Required[K] extends ClassLike ? K : never]: T[K]; +}; + +export declare const fn: ( + implementation?: T | undefined, +) => Mock; + +export declare type FunctionLike = (...args: any) => any; + +export declare type MethodLikeKeys = keyof { + [K in keyof T as Required[K] extends FunctionLike ? K : never]: T[K]; +}; + +/** + * All what the internal typings need is to be sure that we have any-function. + * `FunctionLike` type ensures that and helps to constrain the type as well. + * The default of `UnknownFunction` makes sure that `any`s do not leak to the + * user side. For instance, calling `fn()` without implementation will return + * a mock of `(...args: Array) => unknown` type. If implementation + * is provided, its typings are inferred correctly. + */ +export declare interface Mock + extends Function, + MockInstance { + new (...args: Parameters): ReturnType; + (...args: Parameters): ReturnType; +} + +export declare type Mocked = T extends ClassLike + ? MockedClass + : T extends FunctionLike + ? MockedFunction + : T extends object + ? MockedObject + : T; + +export declare const mocked: { + ( + source: T, + options?: { + shallow: false; + }, + ): Mocked; + ( + source: T_1, + options: { + shallow: true; + }, + ): MockedShallow; +}; + +export declare type MockedClass = MockInstance< + (...args: ConstructorParameters) => Mocked> +> & + MockedObject; + +export declare type MockedFunction = MockInstance & + MockedObject; + +declare type MockedFunctionShallow = MockInstance & + T; + +export declare type MockedObject = { + [K in keyof T]: T[K] extends ClassLike + ? MockedClass + : T[K] extends FunctionLike + ? MockedFunction + : T[K] extends object + ? MockedObject + : T[K]; +} & T; + +declare type MockedObjectShallow = { + [K in keyof T]: T[K] extends ClassLike + ? MockedClass + : T[K] extends FunctionLike + ? MockedFunctionShallow + : T[K]; +} & T; + +export declare type MockedShallow = T extends ClassLike + ? MockedClass + : T extends FunctionLike + ? MockedFunctionShallow + : T extends object + ? MockedObjectShallow + : T; + +export declare type MockFunctionMetadata< + T = unknown, + MetadataType = MockMetadataType, +> = MockMetadata; + +export declare type MockFunctionMetadataType = MockMetadataType; + +declare type MockFunctionResult = + | MockFunctionResultIncomplete + | MockFunctionResultReturn + | MockFunctionResultThrow; + +declare type MockFunctionResultIncomplete = { + type: 'incomplete'; + /** + * Result of a single call to a mock function that has not yet completed. + * This occurs if you test the result from within the mock function itself, + * or from within a function that was called by the mock. + */ + value: undefined; +}; + +declare type MockFunctionResultReturn< + T extends FunctionLike = UnknownFunction, +> = { + type: 'return'; + /** + * Result of a single call to a mock function that returned. + */ + value: ReturnType; +}; + +declare type MockFunctionResultThrow = { + type: 'throw'; + /** + * Result of a single call to a mock function that threw. + */ + value: unknown; +}; + +declare type MockFunctionState = { + /** + * List of the call arguments of all calls that have been made to the mock. + */ + calls: Array>; + /** + * List of all the object instances that have been instantiated from the mock. + */ + instances: Array>; + /** + * List of all the function contexts that have been applied to calls to the mock. + */ + contexts: Array>; + /** + * List of the call order indexes of the mock. Jest is indexing the order of + * invocations of all mocks in a test file. The index is starting with `1`. + */ + invocationCallOrder: Array; + /** + * List of the call arguments of the last call that was made to the mock. + * If the function was not called, it will return `undefined`. + */ + lastCall?: Parameters; + /** + * List of the results of all calls that have been made to the mock. + */ + results: Array>; +}; + +export declare interface MockInstance< + T extends FunctionLike = UnknownFunction, +> { + _isMockFunction: true; + _protoImpl: Function; + getMockImplementation(): T | undefined; + getMockName(): string; + mock: MockFunctionState; + mockClear(): this; + mockReset(): this; + mockRestore(): void; + mockImplementation(fn: T): this; + mockImplementationOnce(fn: T): this; + withImplementation(fn: T, callback: () => Promise): Promise; + withImplementation(fn: T, callback: () => void): void; + mockName(name: string): this; + mockReturnThis(): this; + mockReturnValue(value: ReturnType): this; + mockReturnValueOnce(value: ReturnType): this; + mockResolvedValue(value: ResolveType): this; + mockResolvedValueOnce(value: ResolveType): this; + mockRejectedValue(value: RejectType): this; + mockRejectedValueOnce(value: RejectType): this; +} + +export declare type MockMetadata = { + ref?: number; + members?: Record>; + mockImpl?: T; + name?: string; + refID?: number; + type?: MetadataType; + value?: T; + length?: number; +}; + +export declare type MockMetadataType = + | 'object' + | 'array' + | 'regexp' + | 'function' + | 'constant' + | 'collection' + | 'null' + | 'undefined'; + +export declare class ModuleMocker { + private readonly _environmentGlobal; + private _mockState; + private _mockConfigRegistry; + private _spyState; + private _invocationCallCounter; + /** + * @see README.md + * @param global Global object of the test environment, used to create + * mocks + */ + constructor(global: typeof globalThis); + private _getSlots; + private _ensureMockConfig; + private _ensureMockState; + private _defaultMockConfig; + private _defaultMockState; + private _makeComponent; + private _createMockFunction; + private _generateMock; + /** + * @see README.md + * @param metadata Metadata for the mock in the schema returned by the + * getMetadata method of this module. + */ + generateFromMetadata(metadata: MockMetadata): Mocked; + /** + * @see README.md + * @param component The component for which to retrieve metadata. + */ + getMetadata( + component: T, + _refs?: Map, + ): MockMetadata | null; + isMockFunction( + fn: MockInstance, + ): fn is MockInstance; + isMockFunction

, R>( + fn: (...args: P) => R, + ): fn is Mock<(...args: P) => R>; + isMockFunction(fn: unknown): fn is Mock; + fn(implementation?: T): Mock; + spyOn< + T extends object, + K extends PropertyLikeKeys, + V extends Required[K], + A extends 'get' | 'set', + >( + object: T, + methodKey: K, + accessType: A, + ): A extends 'get' + ? SpiedGetter + : A extends 'set' + ? SpiedSetter + : never; + spyOn< + T extends object, + K extends ConstructorLikeKeys | MethodLikeKeys, + V extends Required[K], + >( + object: T, + methodKey: K, + ): V extends ClassLike | FunctionLike ? Spied : never; + private _spyOnProperty; + clearAllMocks(): void; + resetAllMocks(): void; + restoreAllMocks(): void; + private _typeOf; + mocked( + source: T, + options?: { + shallow: false; + }, + ): Mocked; + mocked( + source: T, + options: { + shallow: true; + }, + ): MockedShallow; +} + +export declare type PropertyLikeKeys = Exclude< + keyof T, + ConstructorLikeKeys | MethodLikeKeys +>; + +declare type RejectType = + ReturnType extends PromiseLike ? unknown : never; + +declare type ResolveType = + ReturnType extends PromiseLike ? U : never; + +export declare type Spied = + T extends ClassLike + ? MockInstance<(...args: ConstructorParameters) => InstanceType> + : T extends FunctionLike + ? MockInstance<(...args: Parameters) => ReturnType> + : never; + +export declare type SpiedClass = + MockInstance<(...args: ConstructorParameters) => InstanceType>; + +export declare type SpiedFunction = + MockInstance<(...args: Parameters) => ReturnType>; + +export declare type SpiedGetter = MockInstance<() => T>; + +export declare type SpiedSetter = MockInstance<(arg: T) => void>; + +export declare interface SpyInstance + extends MockInstance {} + +export declare const spyOn: { + < + T extends object, + K_2 extends Exclude< + keyof T, + | keyof { + [K in keyof T as Required[K] extends ClassLike ? K : never]: T[K]; + } + | keyof { + [K_1 in keyof T as Required[K_1] extends FunctionLike + ? K_1 + : never]: T[K_1]; + } + >, + V extends Required[K_2], + A extends 'set' | 'get', + >( + object: T, + methodKey: K_2, + accessType: A, + ): A extends 'get' + ? SpiedGetter + : A extends 'set' + ? SpiedSetter + : never; + < + T_1 extends object, + K_5 extends + | keyof { + [K_3 in keyof T_1 as Required[K_3] extends ClassLike + ? K_3 + : never]: T_1[K_3]; + } + | keyof { + [K_4 in keyof T_1 as Required[K_4] extends FunctionLike + ? K_4 + : never]: T_1[K_4]; + }, + V_1 extends Required[K_5], + >( + object: T_1, + methodKey: K_5, + ): V_1 extends ClassLike | FunctionLike ? Spied : never; +}; + +export declare type UnknownClass = { + new (...args: Array): unknown; +}; + +export declare type UnknownFunction = (...args: Array) => unknown; + +export {}; diff --git a/node_modules/jest-mock/build/index.js b/node_modules/jest-mock/build/index.js new file mode 100644 index 0000000..deb187e --- /dev/null +++ b/node_modules/jest-mock/build/index.js @@ -0,0 +1,824 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.spyOn = exports.mocked = exports.fn = exports.ModuleMocker = void 0; +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/ban-types-eventually, local/prefer-rest-params-eventually */ + +const MOCK_CONSTRUCTOR_NAME = 'mockConstructor'; +const FUNCTION_NAME_RESERVED_PATTERN = /[\s!-/:-@[-`{-~]/; +const FUNCTION_NAME_RESERVED_REPLACE = new RegExp( + FUNCTION_NAME_RESERVED_PATTERN.source, + 'g' +); +const RESERVED_KEYWORDS = new Set([ + 'arguments', + 'await', + 'break', + 'case', + 'catch', + 'class', + 'const', + 'continue', + 'debugger', + 'default', + 'delete', + 'do', + 'else', + 'enum', + 'eval', + 'export', + 'extends', + 'false', + 'finally', + 'for', + 'function', + 'if', + 'implements', + 'import', + 'in', + 'instanceof', + 'interface', + 'let', + 'new', + 'null', + 'package', + 'private', + 'protected', + 'public', + 'return', + 'static', + 'super', + 'switch', + 'this', + 'throw', + 'true', + 'try', + 'typeof', + 'var', + 'void', + 'while', + 'with', + 'yield' +]); +function matchArity(fn, length) { + let mockConstructor; + switch (length) { + case 1: + mockConstructor = function (_a) { + return fn.apply(this, arguments); + }; + break; + case 2: + mockConstructor = function (_a, _b) { + return fn.apply(this, arguments); + }; + break; + case 3: + mockConstructor = function (_a, _b, _c) { + return fn.apply(this, arguments); + }; + break; + case 4: + mockConstructor = function (_a, _b, _c, _d) { + return fn.apply(this, arguments); + }; + break; + case 5: + mockConstructor = function (_a, _b, _c, _d, _e) { + return fn.apply(this, arguments); + }; + break; + case 6: + mockConstructor = function (_a, _b, _c, _d, _e, _f) { + return fn.apply(this, arguments); + }; + break; + case 7: + mockConstructor = function (_a, _b, _c, _d, _e, _f, _g) { + return fn.apply(this, arguments); + }; + break; + case 8: + mockConstructor = function (_a, _b, _c, _d, _e, _f, _g, _h) { + return fn.apply(this, arguments); + }; + break; + case 9: + mockConstructor = function (_a, _b, _c, _d, _e, _f, _g, _h, _i) { + return fn.apply(this, arguments); + }; + break; + default: + mockConstructor = function () { + return fn.apply(this, arguments); + }; + break; + } + return mockConstructor; +} +function getObjectType(value) { + return Object.prototype.toString.apply(value).slice(8, -1); +} +function getType(ref) { + const typeName = getObjectType(ref); + if ( + typeName === 'Function' || + typeName === 'AsyncFunction' || + typeName === 'GeneratorFunction' || + typeName === 'AsyncGeneratorFunction' + ) { + return 'function'; + } else if (Array.isArray(ref)) { + return 'array'; + } else if (typeName === 'Object') { + return 'object'; + } else if ( + typeName === 'Number' || + typeName === 'String' || + typeName === 'Boolean' || + typeName === 'Symbol' + ) { + return 'constant'; + } else if ( + typeName === 'Map' || + typeName === 'WeakMap' || + typeName === 'Set' + ) { + return 'collection'; + } else if (typeName === 'RegExp') { + return 'regexp'; + } else if (ref === undefined) { + return 'undefined'; + } else if (ref === null) { + return 'null'; + } else { + return null; + } +} +function isReadonlyProp(object, prop) { + if ( + prop === 'arguments' || + prop === 'caller' || + prop === 'callee' || + prop === 'name' || + prop === 'length' + ) { + const typeName = getObjectType(object); + return ( + typeName === 'Function' || + typeName === 'AsyncFunction' || + typeName === 'GeneratorFunction' || + typeName === 'AsyncGeneratorFunction' + ); + } + if ( + prop === 'source' || + prop === 'global' || + prop === 'ignoreCase' || + prop === 'multiline' + ) { + return getObjectType(object) === 'RegExp'; + } + return false; +} +class ModuleMocker { + _environmentGlobal; + _mockState; + _mockConfigRegistry; + _spyState; + _invocationCallCounter; + + /** + * @see README.md + * @param global Global object of the test environment, used to create + * mocks + */ + constructor(global) { + this._environmentGlobal = global; + this._mockState = new WeakMap(); + this._mockConfigRegistry = new WeakMap(); + this._spyState = new Set(); + this._invocationCallCounter = 1; + } + _getSlots(object) { + if (!object) { + return []; + } + const slots = new Set(); + const EnvObjectProto = this._environmentGlobal.Object.prototype; + const EnvFunctionProto = this._environmentGlobal.Function.prototype; + const EnvRegExpProto = this._environmentGlobal.RegExp.prototype; + + // Also check the builtins in the current context as they leak through + // core node modules. + const ObjectProto = Object.prototype; + const FunctionProto = Function.prototype; + const RegExpProto = RegExp.prototype; + + // Properties of Object.prototype, Function.prototype and RegExp.prototype + // are never reported as slots + while ( + object != null && + object !== EnvObjectProto && + object !== EnvFunctionProto && + object !== EnvRegExpProto && + object !== ObjectProto && + object !== FunctionProto && + object !== RegExpProto + ) { + const ownNames = Object.getOwnPropertyNames(object); + for (let i = 0; i < ownNames.length; i++) { + const prop = ownNames[i]; + if (!isReadonlyProp(object, prop)) { + const propDesc = Object.getOwnPropertyDescriptor(object, prop); + if ((propDesc !== undefined && !propDesc.get) || object.__esModule) { + slots.add(prop); + } + } + } + object = Object.getPrototypeOf(object); + } + return Array.from(slots); + } + _ensureMockConfig(f) { + let config = this._mockConfigRegistry.get(f); + if (!config) { + config = this._defaultMockConfig(); + this._mockConfigRegistry.set(f, config); + } + return config; + } + _ensureMockState(f) { + let state = this._mockState.get(f); + if (!state) { + state = this._defaultMockState(); + this._mockState.set(f, state); + } + if (state.calls.length > 0) { + state.lastCall = state.calls[state.calls.length - 1]; + } + return state; + } + _defaultMockConfig() { + return { + mockImpl: undefined, + mockName: 'jest.fn()', + specificMockImpls: [], + specificReturnValues: [] + }; + } + _defaultMockState() { + return { + calls: [], + contexts: [], + instances: [], + invocationCallOrder: [], + results: [] + }; + } + _makeComponent(metadata, restore) { + if (metadata.type === 'object') { + return new this._environmentGlobal.Object(); + } else if (metadata.type === 'array') { + return new this._environmentGlobal.Array(); + } else if (metadata.type === 'regexp') { + return new this._environmentGlobal.RegExp(''); + } else if ( + metadata.type === 'constant' || + metadata.type === 'collection' || + metadata.type === 'null' || + metadata.type === 'undefined' + ) { + return metadata.value; + } else if (metadata.type === 'function') { + const prototype = + (metadata.members && + metadata.members.prototype && + metadata.members.prototype.members) || + {}; + const prototypeSlots = this._getSlots(prototype); + // eslint-disable-next-line @typescript-eslint/no-this-alias + const mocker = this; + const mockConstructor = matchArity(function (...args) { + const mockState = mocker._ensureMockState(f); + const mockConfig = mocker._ensureMockConfig(f); + mockState.instances.push(this); + mockState.contexts.push(this); + mockState.calls.push(args); + // Create and record an "incomplete" mock result immediately upon + // calling rather than waiting for the mock to return. This avoids + // issues caused by recursion where results can be recorded in the + // wrong order. + const mockResult = { + type: 'incomplete', + value: undefined + }; + mockState.results.push(mockResult); + mockState.invocationCallOrder.push(mocker._invocationCallCounter++); + + // Will be set to the return value of the mock if an error is not thrown + let finalReturnValue; + // Will be set to the error that is thrown by the mock (if it throws) + let thrownError; + // Will be set to true if the mock throws an error. The presence of a + // value in `thrownError` is not a 100% reliable indicator because a + // function could throw a value of undefined. + let callDidThrowError = false; + try { + // The bulk of the implementation is wrapped in an immediately + // executed arrow function so the return value of the mock function + // can be easily captured and recorded, despite the many separate + // return points within the logic. + finalReturnValue = (() => { + if (this instanceof f) { + // This is probably being called as a constructor + prototypeSlots.forEach(slot => { + // Copy prototype methods to the instance to make + // it easier to interact with mock instance call and + // return values + if (prototype[slot].type === 'function') { + // @ts-expect-error no index signature + const protoImpl = this[slot]; + // @ts-expect-error no index signature + this[slot] = mocker.generateFromMetadata(prototype[slot]); + // @ts-expect-error no index signature + this[slot]._protoImpl = protoImpl; + } + }); + + // Run the mock constructor implementation + const mockImpl = mockConfig.specificMockImpls.length + ? mockConfig.specificMockImpls.shift() + : mockConfig.mockImpl; + return mockImpl && mockImpl.apply(this, arguments); + } + + // If mockImplementationOnce()/mockImplementation() is last set, + // implementation use the mock + let specificMockImpl = mockConfig.specificMockImpls.shift(); + if (specificMockImpl === undefined) { + specificMockImpl = mockConfig.mockImpl; + } + if (specificMockImpl) { + return specificMockImpl.apply(this, arguments); + } + // Otherwise use prototype implementation + if (f._protoImpl) { + return f._protoImpl.apply(this, arguments); + } + return undefined; + })(); + } catch (error) { + // Store the thrown error so we can record it, then re-throw it. + thrownError = error; + callDidThrowError = true; + throw error; + } finally { + // Record the result of the function. + // NOTE: Intentionally NOT pushing/indexing into the array of mock + // results here to avoid corrupting results data if mockClear() + // is called during the execution of the mock. + // @ts-expect-error reassigning 'incomplete' + mockResult.type = callDidThrowError ? 'throw' : 'return'; + mockResult.value = callDidThrowError ? thrownError : finalReturnValue; + } + return finalReturnValue; + }, metadata.length || 0); + const f = this._createMockFunction(metadata, mockConstructor); + f._isMockFunction = true; + f.getMockImplementation = () => this._ensureMockConfig(f).mockImpl; + if (typeof restore === 'function') { + this._spyState.add(restore); + } + this._mockState.set(f, this._defaultMockState()); + this._mockConfigRegistry.set(f, this._defaultMockConfig()); + Object.defineProperty(f, 'mock', { + configurable: false, + enumerable: true, + get: () => this._ensureMockState(f), + set: val => this._mockState.set(f, val) + }); + f.mockClear = () => { + this._mockState.delete(f); + return f; + }; + f.mockReset = () => { + f.mockClear(); + this._mockConfigRegistry.delete(f); + return f; + }; + f.mockRestore = () => { + f.mockReset(); + return restore ? restore() : undefined; + }; + f.mockReturnValueOnce = value => + // next function call will return this value or default return value + f.mockImplementationOnce(() => value); + f.mockResolvedValueOnce = value => + f.mockImplementationOnce(() => + this._environmentGlobal.Promise.resolve(value) + ); + f.mockRejectedValueOnce = value => + f.mockImplementationOnce(() => + this._environmentGlobal.Promise.reject(value) + ); + f.mockReturnValue = value => + // next function call will return specified return value or this one + f.mockImplementation(() => value); + f.mockResolvedValue = value => + f.mockImplementation(() => + this._environmentGlobal.Promise.resolve(value) + ); + f.mockRejectedValue = value => + f.mockImplementation(() => + this._environmentGlobal.Promise.reject(value) + ); + f.mockImplementationOnce = fn => { + // next function call will use this mock implementation return value + // or default mock implementation return value + const mockConfig = this._ensureMockConfig(f); + mockConfig.specificMockImpls.push(fn); + return f; + }; + f.withImplementation = withImplementation.bind(this); + function withImplementation(fn, callback) { + // Remember previous mock implementation, then set new one + const mockConfig = this._ensureMockConfig(f); + const previousImplementation = mockConfig.mockImpl; + mockConfig.mockImpl = fn; + const returnedValue = callback(); + if ((0, _jestUtil().isPromise)(returnedValue)) { + return returnedValue.then(() => { + mockConfig.mockImpl = previousImplementation; + }); + } else { + mockConfig.mockImpl = previousImplementation; + } + } + f.mockImplementation = fn => { + // next function call will use mock implementation return value + const mockConfig = this._ensureMockConfig(f); + mockConfig.mockImpl = fn; + return f; + }; + f.mockReturnThis = () => + f.mockImplementation(function () { + return this; + }); + f.mockName = name => { + if (name) { + const mockConfig = this._ensureMockConfig(f); + mockConfig.mockName = name; + } + return f; + }; + f.getMockName = () => { + const mockConfig = this._ensureMockConfig(f); + return mockConfig.mockName || 'jest.fn()'; + }; + if (metadata.mockImpl) { + f.mockImplementation(metadata.mockImpl); + } + return f; + } else { + const unknownType = metadata.type || 'undefined type'; + throw new Error(`Unrecognized type ${unknownType}`); + } + } + _createMockFunction(metadata, mockConstructor) { + let name = metadata.name; + if (!name) { + return mockConstructor; + } + + // Preserve `name` property of mocked function. + const boundFunctionPrefix = 'bound '; + let bindCall = ''; + // if-do-while for perf reasons. The common case is for the if to fail. + if (name && name.startsWith(boundFunctionPrefix)) { + do { + name = name.substring(boundFunctionPrefix.length); + // Call bind() just to alter the function name. + bindCall = '.bind(null)'; + } while (name && name.startsWith(boundFunctionPrefix)); + } + + // Special case functions named `mockConstructor` to guard for infinite loops + if (name === MOCK_CONSTRUCTOR_NAME) { + return mockConstructor; + } + if ( + // It's a syntax error to define functions with a reserved keyword as name + RESERVED_KEYWORDS.has(name) || + // It's also a syntax error to define functions with a name that starts with a number + /^\d/.test(name) + ) { + name = `$${name}`; + } + + // It's also a syntax error to define a function with a reserved character + // as part of it's name. + if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) { + name = name.replace(FUNCTION_NAME_RESERVED_REPLACE, '$'); + } + const body = + `return function ${name}() {` + + ` return ${MOCK_CONSTRUCTOR_NAME}.apply(this,arguments);` + + `}${bindCall}`; + const createConstructor = new this._environmentGlobal.Function( + MOCK_CONSTRUCTOR_NAME, + body + ); + return createConstructor(mockConstructor); + } + _generateMock(metadata, callbacks, refs) { + // metadata not compatible but it's the same type, maybe problem with + // overloading of _makeComponent and not _generateMock? + // @ts-expect-error - unsure why TSC complains here? + const mock = this._makeComponent(metadata); + if (metadata.refID != null) { + refs[metadata.refID] = mock; + } + this._getSlots(metadata.members).forEach(slot => { + const slotMetadata = (metadata.members && metadata.members[slot]) || {}; + if (slotMetadata.ref != null) { + callbacks.push( + (function (ref) { + return () => (mock[slot] = refs[ref]); + })(slotMetadata.ref) + ); + } else { + mock[slot] = this._generateMock(slotMetadata, callbacks, refs); + } + }); + if ( + metadata.type !== 'undefined' && + metadata.type !== 'null' && + mock.prototype && + typeof mock.prototype === 'object' + ) { + mock.prototype.constructor = mock; + } + return mock; + } + + /** + * @see README.md + * @param metadata Metadata for the mock in the schema returned by the + * getMetadata method of this module. + */ + generateFromMetadata(metadata) { + const callbacks = []; + const refs = {}; + const mock = this._generateMock(metadata, callbacks, refs); + callbacks.forEach(setter => setter()); + return mock; + } + + /** + * @see README.md + * @param component The component for which to retrieve metadata. + */ + getMetadata(component, _refs) { + const refs = _refs || new Map(); + const ref = refs.get(component); + if (ref != null) { + return { + ref + }; + } + const type = getType(component); + if (!type) { + return null; + } + const metadata = { + type + }; + if ( + type === 'constant' || + type === 'collection' || + type === 'undefined' || + type === 'null' + ) { + metadata.value = component; + return metadata; + } else if (type === 'function') { + // @ts-expect-error component is a function so it has a name, but not + // necessarily a string: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#function_names_in_classes + const componentName = component.name; + if (typeof componentName === 'string') { + metadata.name = componentName; + } + if (this.isMockFunction(component)) { + metadata.mockImpl = component.getMockImplementation(); + } + } + metadata.refID = refs.size; + refs.set(component, metadata.refID); + let members = null; + // Leave arrays alone + if (type !== 'array') { + // @ts-expect-error component is object + this._getSlots(component).forEach(slot => { + if ( + type === 'function' && + this.isMockFunction(component) && + slot.match(/^mock/) + ) { + return; + } + // @ts-expect-error no index signature + const slotMetadata = this.getMetadata(component[slot], refs); + if (slotMetadata) { + if (!members) { + members = {}; + } + members[slot] = slotMetadata; + } + }); + } + if (members) { + metadata.members = members; + } + return metadata; + } + isMockFunction(fn) { + return fn != null && fn._isMockFunction === true; + } + fn(implementation) { + const length = implementation ? implementation.length : 0; + const fn = this._makeComponent({ + length, + type: 'function' + }); + if (implementation) { + fn.mockImplementation(implementation); + } + return fn; + } + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + spyOn(object, methodKey, accessType) { + if (typeof object !== 'object' && typeof object !== 'function') { + throw new Error( + `Cannot spyOn on a primitive value; ${this._typeOf(object)} given` + ); + } + if (!object) { + throw new Error( + `spyOn could not find an object to spy upon for ${String(methodKey)}` + ); + } + if (!methodKey) { + throw new Error('No property name supplied'); + } + if (accessType) { + return this._spyOnProperty(object, methodKey, accessType); + } + const original = object[methodKey]; + if (!this.isMockFunction(original)) { + if (typeof original !== 'function') { + throw new Error( + `Cannot spy the ${String( + methodKey + )} property because it is not a function; ${this._typeOf( + original + )} given instead` + ); + } + const isMethodOwner = Object.prototype.hasOwnProperty.call( + object, + methodKey + ); + let descriptor = Object.getOwnPropertyDescriptor(object, methodKey); + let proto = Object.getPrototypeOf(object); + while (!descriptor && proto !== null) { + descriptor = Object.getOwnPropertyDescriptor(proto, methodKey); + proto = Object.getPrototypeOf(proto); + } + let mock; + if (descriptor && descriptor.get) { + const originalGet = descriptor.get; + mock = this._makeComponent( + { + type: 'function' + }, + () => { + descriptor.get = originalGet; + Object.defineProperty(object, methodKey, descriptor); + } + ); + descriptor.get = () => mock; + Object.defineProperty(object, methodKey, descriptor); + } else { + mock = this._makeComponent( + { + type: 'function' + }, + () => { + if (isMethodOwner) { + object[methodKey] = original; + } else { + delete object[methodKey]; + } + } + ); + // @ts-expect-error overriding original method with a Mock + object[methodKey] = mock; + } + mock.mockImplementation(function () { + return original.apply(this, arguments); + }); + } + return object[methodKey]; + } + _spyOnProperty(obj, propertyKey, accessType) { + let descriptor = Object.getOwnPropertyDescriptor(obj, propertyKey); + let proto = Object.getPrototypeOf(obj); + while (!descriptor && proto !== null) { + descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey); + proto = Object.getPrototypeOf(proto); + } + if (!descriptor) { + throw new Error(`${String(propertyKey)} property does not exist`); + } + if (!descriptor.configurable) { + throw new Error(`${String(propertyKey)} is not declared configurable`); + } + if (!descriptor[accessType]) { + throw new Error( + `Property ${String( + propertyKey + )} does not have access type ${accessType}` + ); + } + const original = descriptor[accessType]; + if (!this.isMockFunction(original)) { + if (typeof original !== 'function') { + throw new Error( + `Cannot spy the ${String( + propertyKey + )} property because it is not a function; ${this._typeOf( + original + )} given instead` + ); + } + descriptor[accessType] = this._makeComponent( + { + type: 'function' + }, + () => { + // @ts-expect-error: mock is assignable + descriptor[accessType] = original; + Object.defineProperty(obj, propertyKey, descriptor); + } + ); + descriptor[accessType].mockImplementation(function () { + // @ts-expect-error - wrong context + return original.apply(this, arguments); + }); + } + Object.defineProperty(obj, propertyKey, descriptor); + return descriptor[accessType]; + } + clearAllMocks() { + this._mockState = new WeakMap(); + } + resetAllMocks() { + this._mockConfigRegistry = new WeakMap(); + this._mockState = new WeakMap(); + } + restoreAllMocks() { + this._spyState.forEach(restore => restore()); + this._spyState = new Set(); + } + _typeOf(value) { + return value == null ? `${value}` : typeof value; + } + mocked(source, _options) { + return source; + } +} +exports.ModuleMocker = ModuleMocker; +const JestMock = new ModuleMocker(globalThis); +const fn = JestMock.fn.bind(JestMock); +exports.fn = fn; +const spyOn = JestMock.spyOn.bind(JestMock); +exports.spyOn = spyOn; +const mocked = JestMock.mocked.bind(JestMock); +exports.mocked = mocked; diff --git a/node_modules/jest-mock/package.json b/node_modules/jest-mock/package.json new file mode 100644 index 0000000..05942f6 --- /dev/null +++ b/node_modules/jest-mock/package.json @@ -0,0 +1,35 @@ +{ + "name": "jest-mock", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-mock" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/types": "^29.2.1", + "@types/node": "*", + "jest-util": "^29.2.1" + }, + "devDependencies": { + "@tsd/typescript": "~4.8.2", + "tsd-lite": "^0.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-pnp-resolver/README.md b/node_modules/jest-pnp-resolver/README.md new file mode 100644 index 0000000..20bf42a --- /dev/null +++ b/node_modules/jest-pnp-resolver/README.md @@ -0,0 +1,34 @@ +# [Plug'n'Play](https://github.com/yarnpkg/rfcs/pull/101) resolver for Jest + +[![npm version](https://img.shields.io/npm/v/jest-pnp-resolver.svg)](https://www.npmjs.com/package/jest-pnp-resolver) +[![node version](https://img.shields.io/node/v/jest-pnp-resolver.svg)](https://www.npmjs.com/package/jest-pnp-resolver) + +*This plugin is also available for Rollup ([rollup-plugin-pnp-resolve](https://github.com/arcanis/rollup-plugin-pnp-resolve)), TypeScript ([ts-pnp](https://github.com/arcanis/ts-pnp)), and Webpack ([pnp-webpack-plugin](https://github.com/arcanis/pnp-webpack-plugin))* + +## Installation + +``` +yarn add -D jest-pnp-resolver +``` + +## Usage + +As of `jest@^24.4.0` you don't need to manually add this package anymore. The default resolver will already use PnP. + +Simply add the resolver to your configuration. For example, a minimal `jest.config.js` would be as such: + +```js +module.exports = { + resolver: require.resolve(`jest-pnp-resolver`) +}; +``` + +## License (MIT) + +> **Copyright © 2016 Maël Nison** +> +> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 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/jest-pnp-resolver/createRequire.js b/node_modules/jest-pnp-resolver/createRequire.js new file mode 100644 index 0000000..7da60d6 --- /dev/null +++ b/node_modules/jest-pnp-resolver/createRequire.js @@ -0,0 +1,25 @@ +const nativeModule = require(`module`); + +module.exports = (filename) => { + // 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.dirname(filename)) + mod._compile(`module.exports = require;`, filename) + return mod.exports +} diff --git a/node_modules/jest-pnp-resolver/getDefaultResolver.js b/node_modules/jest-pnp-resolver/getDefaultResolver.js new file mode 100644 index 0000000..ab90dbc --- /dev/null +++ b/node_modules/jest-pnp-resolver/getDefaultResolver.js @@ -0,0 +1,13 @@ +let defaultResolver; + +module.exports = () => { + if (!defaultResolver) { + try { + defaultResolver = require(`jest-resolve/build/defaultResolver`).default; + } catch (error) { + defaultResolver = require(`jest-resolve/build/default_resolver`).default; + } + } + + return defaultResolver; +}; diff --git a/node_modules/jest-pnp-resolver/index.d.ts b/node_modules/jest-pnp-resolver/index.d.ts new file mode 100644 index 0000000..1acbbac --- /dev/null +++ b/node_modules/jest-pnp-resolver/index.d.ts @@ -0,0 +1,10 @@ +type JestResolverOptions = { + basedir: string; + defaultResolver: (request: string, opts: any) => string, + extensions?: Array, +}; + +export default function resolve( + request: string, + options: JestResolverOptions, +): string; diff --git a/node_modules/jest-pnp-resolver/index.js b/node_modules/jest-pnp-resolver/index.js new file mode 100644 index 0000000..a61a577 --- /dev/null +++ b/node_modules/jest-pnp-resolver/index.js @@ -0,0 +1,49 @@ +let globalPnpApi; +try { + globalPnpApi = require(`pnpapi`); +} catch { + // Just ignore if we don't have a global PnP instance - perhaps + // we'll eventually find one at runtime due to multi-tree +} + +const createRequire = require(`./createRequire`); +const getDefaultResolver = require(`./getDefaultResolver`); + +module.exports = (request, options) => { + const {basedir, defaultResolver, extensions} = options; + + if (process.versions.pnp) { + let pnpApi = globalPnpApi; + + // While technically it would be more correct to run this code + // everytime (since they file being run *may* belong to a + // different dependency tree than the one owning Jest), in + // practice this doesn't happen anywhere else than on the Jest + // repository itself (in the test env). So in order to preserve + // the performances, we can afford a slight incoherence here. + if (!pnpApi) { + try { + const baseReq = createRequire(`${basedir}/internal.js`); + pnpApi = baseReq(`pnpapi`); + } catch { + // The file isn't part of a PnP dependency tree, so we can + // just use the default Jest resolver. + } + } + + if (pnpApi) { + const resolution = pnpApi.resolveRequest(request, `${basedir}/`, {extensions}); + + // When the request is a native module, Jest expects to get the string back unmodified, but pnp returns null instead. + if (resolution === null) + return request; + + return resolution; + } + } + + if (!defaultResolver) + defaultResolver = getDefaultResolver(); + + return defaultResolver(request, {...options, allowPnp: false}); +}; diff --git a/node_modules/jest-pnp-resolver/package.json b/node_modules/jest-pnp-resolver/package.json new file mode 100644 index 0000000..d0e9a6f --- /dev/null +++ b/node_modules/jest-pnp-resolver/package.json @@ -0,0 +1,31 @@ +{ + "name": "jest-pnp-resolver", + "version": "1.2.2", + "description": "plug'n'play resolver for Webpack", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "homepage": "https://github.com/arcanis/jest-pnp-resolver", + "bugs": { + "url": "https://github.com/arcanis/jest-pnp-resolver/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/arcanis/jest-pnp-resolver.git" + }, + "keywords": [ + "jest", + "yarn", + "plugnplay", + "pnp" + ], + "peerDependencies": { + "jest-resolve": "*" + }, + "peerDependenciesMeta": { + "jest-resolve": { + "optional": true + } + } +} diff --git a/node_modules/jest-regex-util/LICENSE b/node_modules/jest-regex-util/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-regex-util/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-regex-util/build/index.d.ts b/node_modules/jest-regex-util/build/index.d.ts new file mode 100644 index 0000000..018afa6 --- /dev/null +++ b/node_modules/jest-regex-util/build/index.d.ts @@ -0,0 +1,20 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ +export declare const escapePathForRegex: (dir: string) => string; + +export declare const escapeStrForRegex: (string: string) => string; + +export declare const replacePathSepForRegex: (string: string) => string; + +export {}; diff --git a/node_modules/jest-regex-util/build/index.js b/node_modules/jest-regex-util/build/index.js new file mode 100644 index 0000000..976143c --- /dev/null +++ b/node_modules/jest-regex-util/build/index.js @@ -0,0 +1,40 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.replacePathSepForRegex = + exports.escapeStrForRegex = + exports.escapePathForRegex = + void 0; +var _path = require('path'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +const escapePathForRegex = dir => { + if (_path.sep === '\\') { + // Replace "\" with "/" so it's not escaped by escapeStrForRegex. + // replacePathSepForRegex will convert it back. + dir = dir.replace(/\\/g, '/'); + } + return replacePathSepForRegex(escapeStrForRegex(dir)); +}; +exports.escapePathForRegex = escapePathForRegex; +const escapeStrForRegex = string => + string.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&'); +exports.escapeStrForRegex = escapeStrForRegex; +const replacePathSepForRegex = string => { + if (_path.sep === '\\') { + return string.replace( + /(\/|(.)?\\(?![[\]{}()*+?.^$|\\]))/g, + (_match, _, p2) => (p2 && p2 !== '\\' ? `${p2}\\\\` : '\\\\') + ); + } + return string; +}; +exports.replacePathSepForRegex = replacePathSepForRegex; diff --git a/node_modules/jest-regex-util/package.json b/node_modules/jest-regex-util/package.json new file mode 100644 index 0000000..28f6799 --- /dev/null +++ b/node_modules/jest-regex-util/package.json @@ -0,0 +1,29 @@ +{ + "name": "jest-regex-util", + "version": "29.2.0", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-regex-util" + }, + "devDependencies": { + "@types/node": "*" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "ee5b37a4f4433afcfffb0356cea47739d8092287" +} diff --git a/node_modules/jest-resolve-dependencies/LICENSE b/node_modules/jest-resolve-dependencies/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-resolve-dependencies/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-resolve-dependencies/build/index.d.ts b/node_modules/jest-resolve-dependencies/build/index.d.ts new file mode 100644 index 0000000..fceba3f --- /dev/null +++ b/node_modules/jest-resolve-dependencies/build/index.d.ts @@ -0,0 +1,43 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {default as default_2} from 'jest-resolve'; +import type {IHasteFS} from 'jest-haste-map'; +import type {ResolveModuleConfig} from 'jest-resolve'; +import {SnapshotResolver} from 'jest-snapshot'; + +/** + * DependencyResolver is used to resolve the direct dependencies of a module or + * to retrieve a list of all transitive inverse dependencies. + */ +export declare class DependencyResolver { + private readonly _hasteFS; + private readonly _resolver; + private readonly _snapshotResolver; + constructor( + resolver: default_2, + hasteFS: IHasteFS, + snapshotResolver: SnapshotResolver, + ); + resolve(file: string, options?: ResolveModuleConfig): Array; + resolveInverseModuleMap( + paths: Set, + filter: (file: string) => boolean, + options?: ResolveModuleConfig, + ): Array; + resolveInverse( + paths: Set, + filter: (file: string) => boolean, + options?: ResolveModuleConfig, + ): Array; +} + +export declare type ResolvedModule = { + file: string; + dependencies: Array; +}; + +export {}; diff --git a/node_modules/jest-resolve-dependencies/build/index.js b/node_modules/jest-resolve-dependencies/build/index.js new file mode 100644 index 0000000..b208ad7 --- /dev/null +++ b/node_modules/jest-resolve-dependencies/build/index.js @@ -0,0 +1,197 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.DependencyResolver = void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _jestSnapshot() { + const data = require('jest-snapshot'); + _jestSnapshot = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * DependencyResolver is used to resolve the direct dependencies of a module or + * to retrieve a list of all transitive inverse dependencies. + */ +class DependencyResolver { + _hasteFS; + _resolver; + _snapshotResolver; + constructor(resolver, hasteFS, snapshotResolver) { + this._resolver = resolver; + this._hasteFS = hasteFS; + this._snapshotResolver = snapshotResolver; + } + resolve(file, options) { + const dependencies = this._hasteFS.getDependencies(file); + if (!dependencies) { + return []; + } + return dependencies.reduce((acc, dependency) => { + if (this._resolver.isCoreModule(dependency)) { + return acc; + } + let resolvedDependency; + let resolvedMockDependency; + try { + resolvedDependency = this._resolver.resolveModule( + file, + dependency, + options + ); + } catch { + try { + resolvedDependency = this._resolver.getMockModule(file, dependency); + } catch { + // leave resolvedDependency as undefined if nothing can be found + } + } + if (resolvedDependency == null) { + return acc; + } + acc.push(resolvedDependency); + + // If we resolve a dependency, then look for a mock dependency + // of the same name in that dependency's directory. + try { + resolvedMockDependency = this._resolver.getMockModule( + resolvedDependency, + path().basename(dependency) + ); + } catch { + // leave resolvedMockDependency as undefined if nothing can be found + } + if (resolvedMockDependency != null) { + const dependencyMockDir = path().resolve( + path().dirname(resolvedDependency), + '__mocks__' + ); + resolvedMockDependency = path().resolve(resolvedMockDependency); + + // make sure mock is in the correct directory + if (dependencyMockDir === path().dirname(resolvedMockDependency)) { + acc.push(resolvedMockDependency); + } + } + return acc; + }, []); + } + resolveInverseModuleMap(paths, filter, options) { + if (!paths.size) { + return []; + } + const collectModules = (related, moduleMap, changed) => { + const visitedModules = new Set(); + const result = []; + while (changed.size) { + changed = new Set( + moduleMap.reduce((acc, module) => { + if ( + visitedModules.has(module.file) || + !module.dependencies.some(dep => changed.has(dep)) + ) { + return acc; + } + const file = module.file; + if (filter(file)) { + result.push(module); + related.delete(file); + } + visitedModules.add(file); + acc.push(file); + return acc; + }, []) + ); + } + return result.concat( + Array.from(related).map(file => ({ + dependencies: [], + file + })) + ); + }; + const relatedPaths = new Set(); + const changed = new Set(); + for (const path of paths) { + if (this._hasteFS.exists(path)) { + const modulePath = (0, _jestSnapshot().isSnapshotPath)(path) + ? this._snapshotResolver.resolveTestPath(path) + : path; + changed.add(modulePath); + if (filter(modulePath)) { + relatedPaths.add(modulePath); + } + } + } + const modules = []; + for (const file of this._hasteFS.getAbsoluteFileIterator()) { + modules.push({ + dependencies: this.resolve(file, options), + file + }); + } + return collectModules(relatedPaths, modules, changed); + } + resolveInverse(paths, filter, options) { + return this.resolveInverseModuleMap(paths, filter, options).map( + module => module.file + ); + } +} +exports.DependencyResolver = DependencyResolver; diff --git a/node_modules/jest-resolve-dependencies/package.json b/node_modules/jest-resolve-dependencies/package.json new file mode 100644 index 0000000..e5aff2a --- /dev/null +++ b/node_modules/jest-resolve-dependencies/package.json @@ -0,0 +1,37 @@ +{ + "name": "jest-resolve-dependencies", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-resolve-dependencies" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "jest-regex-util": "^29.2.0", + "jest-snapshot": "^29.2.2" + }, + "devDependencies": { + "@jest/test-utils": "^29.2.1", + "@jest/types": "^29.2.1", + "jest-haste-map": "^29.2.1", + "jest-resolve": "^29.2.2", + "jest-runtime": "^29.2.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-resolve/LICENSE b/node_modules/jest-resolve/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-resolve/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-resolve/build/ModuleNotFoundError.js b/node_modules/jest-resolve/build/ModuleNotFoundError.js new file mode 100644 index 0000000..59b3f4a --- /dev/null +++ b/node_modules/jest-resolve/build/ModuleNotFoundError.js @@ -0,0 +1,108 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _slash() { + const data = _interopRequireDefault(require('slash')); + _slash = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class ModuleNotFoundError extends Error { + code = 'MODULE_NOT_FOUND'; + hint; + requireStack; + siblingWithSimilarExtensionFound; + moduleName; + _originalMessage; + constructor(message, moduleName) { + super(message); + this._originalMessage = message; + this.moduleName = moduleName; + } + buildMessage(rootDir) { + if (!this._originalMessage) { + this._originalMessage = this.message || ''; + } + let message = this._originalMessage; + if (this.requireStack?.length && this.requireStack.length > 1) { + message += ` + +Require stack: + ${this.requireStack + .map(p => p.replace(`${rootDir}${path().sep}`, '')) + .map(_slash().default) + .join('\n ')} +`; + } + if (this.hint) { + message += this.hint; + } + this.message = message; + } + static duckType(error) { + error.buildMessage = ModuleNotFoundError.prototype.buildMessage; + return error; + } +} +exports.default = ModuleNotFoundError; diff --git a/node_modules/jest-resolve/build/defaultResolver.js b/node_modules/jest-resolve/build/defaultResolver.js new file mode 100644 index 0000000..ca7df16 --- /dev/null +++ b/node_modules/jest-resolve/build/defaultResolver.js @@ -0,0 +1,152 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _path() { + const data = require('path'); + _path = function () { + return data; + }; + return data; +} +function _jestPnpResolver() { + const data = _interopRequireDefault(require('jest-pnp-resolver')); + _jestPnpResolver = function () { + return data; + }; + return data; +} +function _resolve() { + const data = require('resolve'); + _resolve = function () { + return data; + }; + return data; +} +var _resolve2 = require('resolve.exports'); +var _fileWalkers = require('./fileWalkers'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const defaultResolver = (path, options) => { + // Yarn 2 adds support to `resolve` automatically so the pnpResolver is only + // needed for Yarn 1 which implements version 1 of the pnp spec + if (process.versions.pnp === '1') { + return (0, _jestPnpResolver().default)(path, options); + } + const resolveOptions = { + ...options, + isDirectory: _fileWalkers.isDirectory, + isFile: _fileWalkers.isFile, + preserveSymlinks: false, + readPackageSync, + realpathSync: _fileWalkers.realpathSync + }; + const pathToResolve = getPathInModule(path, resolveOptions); + const result = (0, _resolve().sync)(pathToResolve, resolveOptions); + + // Dereference symlinks to ensure we don't create a separate + // module instance depending on how it was referenced. + return (0, _fileWalkers.realpathSync)(result); +}; +var _default = defaultResolver; +/* + * helper functions + */ +exports.default = _default; +function readPackageSync(_, file) { + return (0, _fileWalkers.readPackageCached)(file); +} +function getPathInModule(path, options) { + if (shouldIgnoreRequestForExports(path)) { + return path; + } + const segments = path.split('/'); + let moduleName = segments.shift(); + if (moduleName) { + // TODO: handle `#` here: https://github.com/facebook/jest/issues/12270 + if (moduleName.startsWith('@')) { + moduleName = `${moduleName}/${segments.shift()}`; + } + + // self-reference + const closestPackageJson = (0, _fileWalkers.findClosestPackageJson)( + options.basedir + ); + if (closestPackageJson) { + const pkg = (0, _fileWalkers.readPackageCached)(closestPackageJson); + if (pkg.name === moduleName && pkg.exports) { + const subpath = segments.join('/') || '.'; + const resolved = (0, _resolve2.resolve)( + pkg, + subpath, + createResolveOptions(options.conditions) + ); + if (!resolved) { + throw new Error( + '`exports` exists, but no results - this is a bug in Jest. Please report an issue' + ); + } + return (0, _path().resolve)( + (0, _path().dirname)(closestPackageJson), + resolved + ); + } + } + let packageJsonPath = ''; + try { + packageJsonPath = (0, _resolve().sync)( + `${moduleName}/package.json`, + options + ); + } catch { + // ignore if package.json cannot be found + } + if (packageJsonPath && (0, _fileWalkers.isFile)(packageJsonPath)) { + const pkg = (0, _fileWalkers.readPackageCached)(packageJsonPath); + if (pkg.exports) { + const subpath = segments.join('/') || '.'; + const resolved = (0, _resolve2.resolve)( + pkg, + subpath, + createResolveOptions(options.conditions) + ); + if (!resolved) { + throw new Error( + '`exports` exists, but no results - this is a bug in Jest. Please report an issue' + ); + } + return (0, _path().resolve)( + (0, _path().dirname)(packageJsonPath), + resolved + ); + } + } + } + return path; +} +function createResolveOptions(conditions) { + return conditions + ? { + conditions, + unsafe: true + } + : // no conditions were passed - let's assume this is Jest internal and it should be `require` + { + browser: false, + require: true + }; +} + +// if it's a relative import or an absolute path, exports are ignored +const shouldIgnoreRequestForExports = path => + path.startsWith('.') || (0, _path().isAbsolute)(path); diff --git a/node_modules/jest-resolve/build/fileWalkers.js b/node_modules/jest-resolve/build/fileWalkers.js new file mode 100644 index 0000000..d842691 --- /dev/null +++ b/node_modules/jest-resolve/build/fileWalkers.js @@ -0,0 +1,178 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.clearFsCache = clearFsCache; +exports.findClosestPackageJson = findClosestPackageJson; +exports.isDirectory = isDirectory; +exports.isFile = isFile; +exports.readPackageCached = readPackageCached; +exports.realpathSync = realpathSync; +function _path() { + const data = require('path'); + _path = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function clearFsCache() { + checkedPaths.clear(); + checkedRealpathPaths.clear(); + packageContents.clear(); +} +var IPathType; +(function (IPathType) { + IPathType[(IPathType['FILE'] = 1)] = 'FILE'; + IPathType[(IPathType['DIRECTORY'] = 2)] = 'DIRECTORY'; + IPathType[(IPathType['OTHER'] = 3)] = 'OTHER'; +})(IPathType || (IPathType = {})); +const checkedPaths = new Map(); +function statSyncCached(path) { + const result = checkedPaths.get(path); + if (result != null) { + return result; + } + let stat; + try { + // @ts-expect-error TS2554 - throwIfNoEntry is only available in recent version of node, but inclusion of the option is a backward compatible no-op. + stat = fs().statSync(path, { + throwIfNoEntry: false + }); + } catch (e) { + if (!(e && (e.code === 'ENOENT' || e.code === 'ENOTDIR'))) { + throw e; + } + } + if (stat) { + if (stat.isFile() || stat.isFIFO()) { + checkedPaths.set(path, IPathType.FILE); + return IPathType.FILE; + } else if (stat.isDirectory()) { + checkedPaths.set(path, IPathType.DIRECTORY); + return IPathType.DIRECTORY; + } + } + checkedPaths.set(path, IPathType.OTHER); + return IPathType.OTHER; +} +const checkedRealpathPaths = new Map(); +function realpathCached(path) { + let result = checkedRealpathPaths.get(path); + if (result != null) { + return result; + } + result = (0, _jestUtil().tryRealpath)(path); + checkedRealpathPaths.set(path, result); + if (path !== result) { + // also cache the result in case it's ever referenced directly - no reason to `realpath` that as well + checkedRealpathPaths.set(result, result); + } + return result; +} +const packageContents = new Map(); +function readPackageCached(path) { + let result = packageContents.get(path); + if (result != null) { + return result; + } + result = JSON.parse(fs().readFileSync(path, 'utf8')); + packageContents.set(path, result); + return result; +} + +// adapted from +// https://github.com/lukeed/escalade/blob/2477005062cdbd8407afc90d3f48f4930354252b/src/sync.js +// to use cached `fs` calls +function findClosestPackageJson(start) { + let dir = (0, _path().resolve)('.', start); + if (!isDirectory(dir)) { + dir = (0, _path().dirname)(dir); + } + while (true) { + const pkgJsonFile = (0, _path().resolve)(dir, './package.json'); + const hasPackageJson = isFile(pkgJsonFile); + if (hasPackageJson) { + return pkgJsonFile; + } + const prevDir = dir; + dir = (0, _path().dirname)(dir); + if (prevDir === dir) { + return undefined; + } + } +} + +/* + * helper functions + */ +function isFile(file) { + return statSyncCached(file) === IPathType.FILE; +} +function isDirectory(dir) { + return statSyncCached(dir) === IPathType.DIRECTORY; +} +function realpathSync(file) { + return realpathCached(file); +} diff --git a/node_modules/jest-resolve/build/index.d.ts b/node_modules/jest-resolve/build/index.d.ts new file mode 100644 index 0000000..0d0af60 --- /dev/null +++ b/node_modules/jest-resolve/build/index.d.ts @@ -0,0 +1,319 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {IModuleMap} from 'jest-haste-map'; + +export declare type AsyncResolver = ( + path: string, + options: ResolverOptions, +) => Promise; + +declare function cachedShouldLoadAsEsm( + path: string, + extensionsToTreatAsEsm: Array, +): boolean; + +declare const defaultResolver: SyncResolver; + +export declare type FindNodeModuleConfig = { + basedir: string; + conditions?: Array; + extensions?: Array; + moduleDirectory?: Array; + paths?: Array; + resolver?: string | null; + rootDir?: string; + throwIfNotFound?: boolean; +}; + +export declare type JestResolver = ResolverSyncObject | ResolverAsyncObject; + +declare interface JSONObject { + [key: string]: JSONValue; +} + +declare type JSONValue = + | string + | number + | boolean + | JSONObject + | Array; + +declare type ModuleNameMapperConfig = { + regex: RegExp; + moduleName: string | Array; +}; + +declare class ModuleNotFoundError extends Error { + code: string; + hint?: string; + requireStack?: Array; + siblingWithSimilarExtensionFound?: boolean; + moduleName?: string; + private _originalMessage?; + constructor(message: string, moduleName?: string); + buildMessage(rootDir: string): void; + static duckType(error: ModuleNotFoundError): ModuleNotFoundError; +} + +/** + * Allows transforming parsed `package.json` contents. + * + * @param pkg - Parsed `package.json` contents. + * @param file - Path to `package.json` file. + * @param dir - Directory that contains the `package.json`. + * + * @returns Transformed `package.json` contents. + */ +export declare type PackageFilter = ( + pkg: PackageJSON, + file: string, + dir: string, +) => PackageJSON; + +export declare type PackageJSON = JSONObject; + +/** + * Allows transforming a path within a package. + * + * @param pkg - Parsed `package.json` contents. + * @param path - Path being resolved. + * @param relativePath - Path relative from the `package.json` location. + * + * @returns Relative path that will be joined from the `package.json` location. + */ +export declare type PathFilter = ( + pkg: PackageJSON, + path: string, + relativePath: string, +) => string; + +export declare type ResolveModuleConfig = { + conditions?: Array; + skipNodeResolution?: boolean; + paths?: Array; +}; + +declare class Resolver { + private readonly _options; + private readonly _moduleMap; + private readonly _moduleIDCache; + private readonly _moduleNameCache; + private readonly _modulePathCache; + private readonly _supportsNativePlatform; + constructor(moduleMap: IModuleMap, options: ResolverConfig); + static ModuleNotFoundError: typeof ModuleNotFoundError; + static tryCastModuleNotFoundError(error: unknown): ModuleNotFoundError | null; + static clearDefaultResolverCache(): void; + static findNodeModule( + path: string, + options: FindNodeModuleConfig, + ): string | null; + static findNodeModuleAsync( + path: string, + options: FindNodeModuleConfig, + ): Promise; + static unstable_shouldLoadAsEsm: typeof cachedShouldLoadAsEsm; + resolveModuleFromDirIfExists( + dirname: string, + moduleName: string, + options?: ResolveModuleConfig, + ): string | null; + resolveModuleFromDirIfExistsAsync( + dirname: string, + moduleName: string, + options?: ResolveModuleConfig, + ): Promise; + resolveModule( + from: string, + moduleName: string, + options?: ResolveModuleConfig, + ): string; + resolveModuleAsync( + from: string, + moduleName: string, + options?: ResolveModuleConfig, + ): Promise; + /** + * _prepareForResolution is shared between the sync and async module resolution + * methods, to try to keep them as DRY as possible. + */ + private _prepareForResolution; + /** + * _getHasteModulePath attempts to return the path to a haste module. + */ + private _getHasteModulePath; + private _throwModNotFoundError; + private _getMapModuleName; + private _isAliasModule; + isCoreModule(moduleName: string): boolean; + getModule(name: string): string | null; + getModulePath(from: string, moduleName: string): string; + getPackage(name: string): string | null; + getMockModule(from: string, name: string): string | null; + getMockModuleAsync(from: string, name: string): Promise; + getModulePaths(from: string): Array; + getModuleID( + virtualMocks: Map, + from: string, + moduleName?: string, + options?: ResolveModuleConfig, + ): string; + getModuleIDAsync( + virtualMocks: Map, + from: string, + moduleName?: string, + options?: ResolveModuleConfig, + ): Promise; + private _getModuleType; + private _getAbsolutePath; + private _getAbsolutePathAsync; + private _getMockPath; + private _getMockPathAsync; + private _getVirtualMockPath; + private _getVirtualMockPathAsync; + private _isModuleResolved; + private _isModuleResolvedAsync; + resolveStubModuleName(from: string, moduleName: string): string | null; + resolveStubModuleNameAsync( + from: string, + moduleName: string, + ): Promise; +} +export default Resolver; + +declare type ResolverAsyncObject = { + sync?: SyncResolver; + async: AsyncResolver; +}; + +declare type ResolverConfig = { + defaultPlatform?: string | null; + extensions: Array; + hasCoreModules: boolean; + moduleDirectories: Array; + moduleNameMapper?: Array | null; + modulePaths?: Array; + platforms?: Array; + resolver?: string | null; + rootDir: string; +}; + +export declare type ResolverOptions = { + /** Directory to begin resolving from. */ + basedir: string; + /** List of export conditions. */ + conditions?: Array; + /** Instance of default resolver. */ + defaultResolver: typeof defaultResolver; + /** List of file extensions to search in order. */ + extensions?: Array; + /** + * List of directory names to be looked up for modules recursively. + * + * @defaultValue + * The default is `['node_modules']`. + */ + moduleDirectory?: Array; + /** + * List of `require.paths` to use if nothing is found in `node_modules`. + * + * @defaultValue + * The default is `undefined`. + */ + paths?: Array; + /** Allows transforming parsed `package.json` contents. */ + packageFilter?: PackageFilter; + /** Allows transforms a path within a package. */ + pathFilter?: PathFilter; + /** Current root directory. */ + rootDir?: string; +}; + +declare type ResolverSyncObject = { + sync: SyncResolver; + async?: AsyncResolver; +}; + +/** + * Finds the runner to use: + * + * 1. looks for jest-runner- relative to project. + * 1. looks for jest-runner- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ +export declare const resolveRunner: ( + resolver: string | undefined | null, + { + filePath, + rootDir, + requireResolveFunction, + }: { + filePath: string; + rootDir: string; + requireResolveFunction: (moduleName: string) => string; + }, +) => string; + +export declare const resolveSequencer: ( + resolver: string | undefined | null, + { + filePath, + rootDir, + requireResolveFunction, + }: { + filePath: string; + rootDir: string; + requireResolveFunction: (moduleName: string) => string; + }, +) => string; + +/** + * Finds the test environment to use: + * + * 1. looks for jest-environment- relative to project. + * 1. looks for jest-environment- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ +export declare const resolveTestEnvironment: ({ + rootDir, + testEnvironment: filePath, + requireResolveFunction, +}: { + rootDir: string; + testEnvironment: string; + requireResolveFunction: (moduleName: string) => string; +}) => string; + +/** + * Finds the watch plugins to use: + * + * 1. looks for jest-watch- relative to project. + * 1. looks for jest-watch- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ +export declare const resolveWatchPlugin: ( + resolver: string | undefined | null, + { + filePath, + rootDir, + requireResolveFunction, + }: { + filePath: string; + rootDir: string; + requireResolveFunction: (moduleName: string) => string; + }, +) => string; + +export declare type SyncResolver = ( + path: string, + options: ResolverOptions, +) => string; + +export {}; diff --git a/node_modules/jest-resolve/build/index.js b/node_modules/jest-resolve/build/index.js new file mode 100644 index 0000000..c955640 --- /dev/null +++ b/node_modules/jest-resolve/build/index.js @@ -0,0 +1,31 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +var _exportNames = {}; +exports.default = void 0; +var _resolver = _interopRequireDefault(require('./resolver')); +var _utils = require('./utils'); +Object.keys(_utils).forEach(function (key) { + if (key === 'default' || key === '__esModule') return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _utils[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _utils[key]; + } + }); +}); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var _default = _resolver.default; +exports.default = _default; diff --git a/node_modules/jest-resolve/build/isBuiltinModule.js b/node_modules/jest-resolve/build/isBuiltinModule.js new file mode 100644 index 0000000..e5da579 --- /dev/null +++ b/node_modules/jest-resolve/build/isBuiltinModule.js @@ -0,0 +1,27 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = isBuiltinModule; +function _module() { + const data = _interopRequireDefault(require('module')); + _module = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const BUILTIN_MODULES = new Set(_module().default.builtinModules); +function isBuiltinModule(module) { + return BUILTIN_MODULES.has(module); +} diff --git a/node_modules/jest-resolve/build/nodeModulesPaths.js b/node_modules/jest-resolve/build/nodeModulesPaths.js new file mode 100644 index 0000000..d26ba46 --- /dev/null +++ b/node_modules/jest-resolve/build/nodeModulesPaths.js @@ -0,0 +1,117 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = nodeModulesPaths; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * Adapted from: https://github.com/substack/node-resolve + */ + +function nodeModulesPaths(basedir, options) { + const modules = + options && options.moduleDirectory + ? Array.from(options.moduleDirectory) + : ['node_modules']; + + // ensure that `basedir` is an absolute path at this point, + // resolving against the process' current working directory + const basedirAbs = path().resolve(basedir); + let prefix = '/'; + if (/^([A-Za-z]:)/.test(basedirAbs)) { + prefix = ''; + } else if (/^\\\\/.test(basedirAbs)) { + prefix = '\\\\'; + } + + // The node resolution algorithm (as implemented by NodeJS and TypeScript) + // traverses parents of the physical path, not the symlinked path + let physicalBasedir; + try { + physicalBasedir = (0, _jestUtil().tryRealpath)(basedirAbs); + } catch { + // realpath can throw, e.g. on mapped drives + physicalBasedir = basedirAbs; + } + const paths = [physicalBasedir]; + let parsed = path().parse(physicalBasedir); + while (parsed.dir !== paths[paths.length - 1]) { + paths.push(parsed.dir); + parsed = path().parse(parsed.dir); + } + const dirs = paths + .reduce( + (dirs, aPath) => + dirs.concat( + modules.map(moduleDir => + path().isAbsolute(moduleDir) + ? aPath === basedirAbs + ? moduleDir + : '' + : path().join(prefix, aPath, moduleDir) + ) + ), + [] + ) + .filter(dir => dir !== ''); + return options.paths ? dirs.concat(options.paths) : dirs; +} diff --git a/node_modules/jest-resolve/build/resolver.js b/node_modules/jest-resolve/build/resolver.js new file mode 100644 index 0000000..bc3b7fa --- /dev/null +++ b/node_modules/jest-resolve/build/resolver.js @@ -0,0 +1,789 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _slash() { + const data = _interopRequireDefault(require('slash')); + _slash = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _ModuleNotFoundError = _interopRequireDefault( + require('./ModuleNotFoundError') +); +var _defaultResolver = _interopRequireDefault(require('./defaultResolver')); +var _fileWalkers = require('./fileWalkers'); +var _isBuiltinModule = _interopRequireDefault(require('./isBuiltinModule')); +var _nodeModulesPaths = _interopRequireDefault(require('./nodeModulesPaths')); +var _shouldLoadAsEsm = _interopRequireWildcard(require('./shouldLoadAsEsm')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/* eslint-disable local/prefer-spread-eventually */ + +const NATIVE_PLATFORM = 'native'; + +// We might be inside a symlink. +const resolvedCwd = (0, _jestUtil().tryRealpath)(process.cwd()); +const {NODE_PATH} = process.env; +const nodePaths = NODE_PATH + ? NODE_PATH.split(path().delimiter) + .filter(Boolean) + // The resolver expects absolute paths. + .map(p => path().resolve(resolvedCwd, p)) + : undefined; +class Resolver { + _options; + _moduleMap; + _moduleIDCache; + _moduleNameCache; + _modulePathCache; + _supportsNativePlatform; + constructor(moduleMap, options) { + this._options = { + defaultPlatform: options.defaultPlatform, + extensions: options.extensions, + hasCoreModules: + options.hasCoreModules === undefined ? true : options.hasCoreModules, + moduleDirectories: options.moduleDirectories || ['node_modules'], + moduleNameMapper: options.moduleNameMapper, + modulePaths: options.modulePaths, + platforms: options.platforms, + resolver: options.resolver, + rootDir: options.rootDir + }; + this._supportsNativePlatform = options.platforms + ? options.platforms.includes(NATIVE_PLATFORM) + : false; + this._moduleMap = moduleMap; + this._moduleIDCache = new Map(); + this._moduleNameCache = new Map(); + this._modulePathCache = new Map(); + } + static ModuleNotFoundError = _ModuleNotFoundError.default; + static tryCastModuleNotFoundError(error) { + if (error instanceof _ModuleNotFoundError.default) { + return error; + } + const casted = error; + if (casted.code === 'MODULE_NOT_FOUND') { + return _ModuleNotFoundError.default.duckType(casted); + } + return null; + } + static clearDefaultResolverCache() { + (0, _fileWalkers.clearFsCache)(); + (0, _shouldLoadAsEsm.clearCachedLookups)(); + } + static findNodeModule(path, options) { + const resolverModule = loadResolver(options.resolver); + let resolver = _defaultResolver.default; + if (typeof resolverModule === 'function') { + resolver = resolverModule; + } else if (typeof resolverModule.sync === 'function') { + resolver = resolverModule.sync; + } + const paths = options.paths; + try { + return resolver(path, { + basedir: options.basedir, + conditions: options.conditions, + defaultResolver: _defaultResolver.default, + extensions: options.extensions, + moduleDirectory: options.moduleDirectory, + paths: paths ? (nodePaths || []).concat(paths) : nodePaths, + rootDir: options.rootDir + }); + } catch (e) { + if (options.throwIfNotFound) { + throw e; + } + } + return null; + } + static async findNodeModuleAsync(path, options) { + const resolverModule = loadResolver(options.resolver); + let resolver = _defaultResolver.default; + if (typeof resolverModule === 'function') { + resolver = resolverModule; + } else if ( + typeof resolverModule.async === 'function' || + typeof resolverModule.sync === 'function' + ) { + const asyncOrSync = resolverModule.async || resolverModule.sync; + if (asyncOrSync == null) { + throw new Error(`Unable to load resolver at ${options.resolver}`); + } + resolver = asyncOrSync; + } + const paths = options.paths; + try { + const result = await resolver(path, { + basedir: options.basedir, + conditions: options.conditions, + defaultResolver: _defaultResolver.default, + extensions: options.extensions, + moduleDirectory: options.moduleDirectory, + paths: paths ? (nodePaths || []).concat(paths) : nodePaths, + rootDir: options.rootDir + }); + return result; + } catch (e) { + if (options.throwIfNotFound) { + throw e; + } + } + return null; + } + + // unstable as it should be replaced by https://github.com/nodejs/modules/issues/393, and we don't want people to use it + static unstable_shouldLoadAsEsm = _shouldLoadAsEsm.default; + resolveModuleFromDirIfExists(dirname, moduleName, options) { + const {extensions, key, moduleDirectory, paths, skipResolution} = + this._prepareForResolution(dirname, moduleName, options); + let module; + + // 1. If we have already resolved this module for this directory name, + // return a value from the cache. + const cacheResult = this._moduleNameCache.get(key); + if (cacheResult) { + return cacheResult; + } + + // 2. Check if the module is a haste module. + module = this.getModule(moduleName); + if (module) { + this._moduleNameCache.set(key, module); + return module; + } + + // 3. Check if the module is a node module and resolve it based on + // the node module resolution algorithm. If skipNodeResolution is given we + // ignore all modules that look like node modules (ie. are not relative + // requires). This enables us to speed up resolution when we build a + // dependency graph because we don't have to look at modules that may not + // exist and aren't mocked. + const resolveNodeModule = (name, throwIfNotFound = false) => { + // Only skip default resolver + if (this.isCoreModule(name) && !this._options.resolver) { + return name; + } + return Resolver.findNodeModule(name, { + basedir: dirname, + conditions: options?.conditions, + extensions, + moduleDirectory, + paths, + resolver: this._options.resolver, + rootDir: this._options.rootDir, + throwIfNotFound + }); + }; + if (!skipResolution) { + module = resolveNodeModule(moduleName, Boolean(process.versions.pnp)); + if (module) { + this._moduleNameCache.set(key, module); + return module; + } + } + + // 4. Resolve "haste packages" which are `package.json` files outside of + // `node_modules` folders anywhere in the file system. + try { + const hasteModulePath = this._getHasteModulePath(moduleName); + if (hasteModulePath) { + // try resolving with custom resolver first to support extensions, + // then fallback to require.resolve + const resolvedModule = + resolveNodeModule(hasteModulePath) || + require.resolve(hasteModulePath); + this._moduleNameCache.set(key, resolvedModule); + return resolvedModule; + } + } catch {} + return null; + } + async resolveModuleFromDirIfExistsAsync(dirname, moduleName, options) { + const {extensions, key, moduleDirectory, paths, skipResolution} = + this._prepareForResolution(dirname, moduleName, options); + let module; + + // 1. If we have already resolved this module for this directory name, + // return a value from the cache. + const cacheResult = this._moduleNameCache.get(key); + if (cacheResult) { + return cacheResult; + } + + // 2. Check if the module is a haste module. + module = this.getModule(moduleName); + if (module) { + this._moduleNameCache.set(key, module); + return module; + } + + // 3. Check if the module is a node module and resolve it based on + // the node module resolution algorithm. If skipNodeResolution is given we + // ignore all modules that look like node modules (ie. are not relative + // requires). This enables us to speed up resolution when we build a + // dependency graph because we don't have to look at modules that may not + // exist and aren't mocked. + const resolveNodeModule = async (name, throwIfNotFound = false) => { + // Only skip default resolver + if (this.isCoreModule(name) && !this._options.resolver) { + return name; + } + return Resolver.findNodeModuleAsync(name, { + basedir: dirname, + conditions: options?.conditions, + extensions, + moduleDirectory, + paths, + resolver: this._options.resolver, + rootDir: this._options.rootDir, + throwIfNotFound + }); + }; + if (!skipResolution) { + module = await resolveNodeModule( + moduleName, + Boolean(process.versions.pnp) + ); + if (module) { + this._moduleNameCache.set(key, module); + return module; + } + } + + // 4. Resolve "haste packages" which are `package.json` files outside of + // `node_modules` folders anywhere in the file system. + try { + const hasteModulePath = this._getHasteModulePath(moduleName); + if (hasteModulePath) { + // try resolving with custom resolver first to support extensions, + // then fallback to require.resolve + const resolvedModule = + (await resolveNodeModule(hasteModulePath)) || + // QUESTION: should this be async? + require.resolve(hasteModulePath); + this._moduleNameCache.set(key, resolvedModule); + return resolvedModule; + } + } catch {} + return null; + } + resolveModule(from, moduleName, options) { + const dirname = path().dirname(from); + const module = + this.resolveStubModuleName(from, moduleName) || + this.resolveModuleFromDirIfExists(dirname, moduleName, options); + if (module) return module; + + // 5. Throw an error if the module could not be found. `resolve.sync` only + // produces an error based on the dirname but we have the actual current + // module name available. + this._throwModNotFoundError(from, moduleName); + } + async resolveModuleAsync(from, moduleName, options) { + const dirname = path().dirname(from); + const module = + (await this.resolveStubModuleNameAsync(from, moduleName)) || + (await this.resolveModuleFromDirIfExistsAsync( + dirname, + moduleName, + options + )); + if (module) return module; + + // 5. Throw an error if the module could not be found. `resolve` only + // produces an error based on the dirname but we have the actual current + // module name available. + this._throwModNotFoundError(from, moduleName); + } + + /** + * _prepareForResolution is shared between the sync and async module resolution + * methods, to try to keep them as DRY as possible. + */ + _prepareForResolution(dirname, moduleName, options) { + const paths = options?.paths || this._options.modulePaths; + const moduleDirectory = this._options.moduleDirectories; + const stringifiedOptions = options ? JSON.stringify(options) : ''; + const key = dirname + path().delimiter + moduleName + stringifiedOptions; + const defaultPlatform = this._options.defaultPlatform; + const extensions = this._options.extensions.slice(); + if (this._supportsNativePlatform) { + extensions.unshift( + ...this._options.extensions.map(ext => `.${NATIVE_PLATFORM}${ext}`) + ); + } + if (defaultPlatform) { + extensions.unshift( + ...this._options.extensions.map(ext => `.${defaultPlatform}${ext}`) + ); + } + const skipResolution = + options && options.skipNodeResolution && !moduleName.includes(path().sep); + return { + extensions, + key, + moduleDirectory, + paths, + skipResolution + }; + } + + /** + * _getHasteModulePath attempts to return the path to a haste module. + */ + _getHasteModulePath(moduleName) { + const parts = moduleName.split('/'); + const hastePackage = this.getPackage(parts.shift()); + if (hastePackage) { + return path().join.apply( + path(), + [path().dirname(hastePackage)].concat(parts) + ); + } + return null; + } + _throwModNotFoundError(from, moduleName) { + const relativePath = + (0, _slash().default)(path().relative(this._options.rootDir, from)) || + '.'; + throw new _ModuleNotFoundError.default( + `Cannot find module '${moduleName}' from '${relativePath}'`, + moduleName + ); + } + _getMapModuleName(matches) { + return matches + ? moduleName => + moduleName.replace( + /\$([0-9]+)/g, + (_, index) => matches[parseInt(index, 10)] + ) + : moduleName => moduleName; + } + _isAliasModule(moduleName) { + const moduleNameMapper = this._options.moduleNameMapper; + if (!moduleNameMapper) { + return false; + } + return moduleNameMapper.some(({regex}) => regex.test(moduleName)); + } + isCoreModule(moduleName) { + return ( + this._options.hasCoreModules && + ((0, _isBuiltinModule.default)(moduleName) || + (moduleName.startsWith('node:') && + (0, _isBuiltinModule.default)(moduleName.slice('node:'.length)))) && + !this._isAliasModule(moduleName) + ); + } + getModule(name) { + return this._moduleMap.getModule( + name, + this._options.defaultPlatform, + this._supportsNativePlatform + ); + } + getModulePath(from, moduleName) { + if (moduleName[0] !== '.' || path().isAbsolute(moduleName)) { + return moduleName; + } + return path().normalize(`${path().dirname(from)}/${moduleName}`); + } + getPackage(name) { + return this._moduleMap.getPackage( + name, + this._options.defaultPlatform, + this._supportsNativePlatform + ); + } + getMockModule(from, name) { + const mock = this._moduleMap.getMockModule(name); + if (mock) { + return mock; + } else { + const moduleName = this.resolveStubModuleName(from, name); + if (moduleName) { + return this.getModule(moduleName) || moduleName; + } + } + return null; + } + async getMockModuleAsync(from, name) { + const mock = this._moduleMap.getMockModule(name); + if (mock) { + return mock; + } else { + const moduleName = await this.resolveStubModuleNameAsync(from, name); + if (moduleName) { + return this.getModule(moduleName) || moduleName; + } + } + return null; + } + getModulePaths(from) { + const cachedModule = this._modulePathCache.get(from); + if (cachedModule) { + return cachedModule; + } + const moduleDirectory = this._options.moduleDirectories; + const paths = (0, _nodeModulesPaths.default)(from, { + moduleDirectory + }); + if (paths[paths.length - 1] === undefined) { + // circumvent node-resolve bug that adds `undefined` as last item. + paths.pop(); + } + this._modulePathCache.set(from, paths); + return paths; + } + getModuleID(virtualMocks, from, moduleName = '', options) { + const stringifiedOptions = options ? JSON.stringify(options) : ''; + const key = from + path().delimiter + moduleName + stringifiedOptions; + const cachedModuleID = this._moduleIDCache.get(key); + if (cachedModuleID) { + return cachedModuleID; + } + const moduleType = this._getModuleType(moduleName); + const absolutePath = this._getAbsolutePath( + virtualMocks, + from, + moduleName, + options + ); + const mockPath = this._getMockPath(from, moduleName); + const sep = path().delimiter; + const id = + moduleType + + sep + + (absolutePath ? absolutePath + sep : '') + + (mockPath ? mockPath + sep : '') + + (stringifiedOptions ? stringifiedOptions + sep : ''); + this._moduleIDCache.set(key, id); + return id; + } + async getModuleIDAsync(virtualMocks, from, moduleName = '', options) { + const stringifiedOptions = options ? JSON.stringify(options) : ''; + const key = from + path().delimiter + moduleName + stringifiedOptions; + const cachedModuleID = this._moduleIDCache.get(key); + if (cachedModuleID) { + return cachedModuleID; + } + if (moduleName.startsWith('data:')) { + return moduleName; + } + const moduleType = this._getModuleType(moduleName); + const absolutePath = await this._getAbsolutePathAsync( + virtualMocks, + from, + moduleName, + options + ); + const mockPath = await this._getMockPathAsync(from, moduleName); + const sep = path().delimiter; + const id = + moduleType + + sep + + (absolutePath ? absolutePath + sep : '') + + (mockPath ? mockPath + sep : '') + + (stringifiedOptions ? stringifiedOptions + sep : ''); + this._moduleIDCache.set(key, id); + return id; + } + _getModuleType(moduleName) { + return this.isCoreModule(moduleName) ? 'node' : 'user'; + } + _getAbsolutePath(virtualMocks, from, moduleName, options) { + if (this.isCoreModule(moduleName)) { + return moduleName; + } + if (moduleName.startsWith('data:')) { + return moduleName; + } + return this._isModuleResolved(from, moduleName) + ? this.getModule(moduleName) + : this._getVirtualMockPath(virtualMocks, from, moduleName, options); + } + async _getAbsolutePathAsync(virtualMocks, from, moduleName, options) { + if (this.isCoreModule(moduleName)) { + return moduleName; + } + if (moduleName.startsWith('data:')) { + return moduleName; + } + const isModuleResolved = await this._isModuleResolvedAsync( + from, + moduleName + ); + return isModuleResolved + ? this.getModule(moduleName) + : this._getVirtualMockPathAsync(virtualMocks, from, moduleName, options); + } + _getMockPath(from, moduleName) { + return !this.isCoreModule(moduleName) + ? this.getMockModule(from, moduleName) + : null; + } + async _getMockPathAsync(from, moduleName) { + return !this.isCoreModule(moduleName) + ? this.getMockModuleAsync(from, moduleName) + : null; + } + _getVirtualMockPath(virtualMocks, from, moduleName, options) { + const virtualMockPath = this.getModulePath(from, moduleName); + return virtualMocks.get(virtualMockPath) + ? virtualMockPath + : moduleName + ? this.resolveModule(from, moduleName, options) + : from; + } + async _getVirtualMockPathAsync(virtualMocks, from, moduleName, options) { + const virtualMockPath = this.getModulePath(from, moduleName); + return virtualMocks.get(virtualMockPath) + ? virtualMockPath + : moduleName + ? this.resolveModuleAsync(from, moduleName, options) + : from; + } + _isModuleResolved(from, moduleName) { + return !!( + this.getModule(moduleName) || this.getMockModule(from, moduleName) + ); + } + async _isModuleResolvedAsync(from, moduleName) { + return !!( + this.getModule(moduleName) || + (await this.getMockModuleAsync(from, moduleName)) + ); + } + resolveStubModuleName(from, moduleName) { + const dirname = path().dirname(from); + const {extensions, moduleDirectory, paths} = this._prepareForResolution( + dirname, + moduleName + ); + const moduleNameMapper = this._options.moduleNameMapper; + const resolver = this._options.resolver; + if (moduleNameMapper) { + for (const {moduleName: mappedModuleName, regex} of moduleNameMapper) { + if (regex.test(moduleName)) { + // Note: once a moduleNameMapper matches the name, it must result + // in a module, or else an error is thrown. + const matches = moduleName.match(regex); + const mapModuleName = this._getMapModuleName(matches); + const possibleModuleNames = Array.isArray(mappedModuleName) + ? mappedModuleName + : [mappedModuleName]; + let module = null; + for (const possibleModuleName of possibleModuleNames) { + const updatedName = mapModuleName(possibleModuleName); + module = + this.getModule(updatedName) || + Resolver.findNodeModule(updatedName, { + basedir: dirname, + extensions, + moduleDirectory, + paths, + resolver, + rootDir: this._options.rootDir + }); + if (module) { + break; + } + } + if (!module) { + throw createNoMappedModuleFoundError( + moduleName, + mapModuleName, + mappedModuleName, + regex, + resolver + ); + } + return module; + } + } + } + return null; + } + async resolveStubModuleNameAsync(from, moduleName) { + const dirname = path().dirname(from); + const {extensions, moduleDirectory, paths} = this._prepareForResolution( + dirname, + moduleName + ); + const moduleNameMapper = this._options.moduleNameMapper; + const resolver = this._options.resolver; + if (moduleNameMapper) { + for (const {moduleName: mappedModuleName, regex} of moduleNameMapper) { + if (regex.test(moduleName)) { + // Note: once a moduleNameMapper matches the name, it must result + // in a module, or else an error is thrown. + const matches = moduleName.match(regex); + const mapModuleName = this._getMapModuleName(matches); + const possibleModuleNames = Array.isArray(mappedModuleName) + ? mappedModuleName + : [mappedModuleName]; + let module = null; + for (const possibleModuleName of possibleModuleNames) { + const updatedName = mapModuleName(possibleModuleName); + module = + this.getModule(updatedName) || + (await Resolver.findNodeModuleAsync(updatedName, { + basedir: dirname, + extensions, + moduleDirectory, + paths, + resolver, + rootDir: this._options.rootDir + })); + if (module) { + break; + } + } + if (!module) { + throw createNoMappedModuleFoundError( + moduleName, + mapModuleName, + mappedModuleName, + regex, + resolver + ); + } + return module; + } + } + } + return null; + } +} +exports.default = Resolver; +const createNoMappedModuleFoundError = ( + moduleName, + mapModuleName, + mappedModuleName, + regex, + resolver +) => { + const mappedAs = Array.isArray(mappedModuleName) + ? JSON.stringify(mappedModuleName.map(mapModuleName), null, 2) + : mappedModuleName; + const original = Array.isArray(mappedModuleName) + ? `${ + JSON.stringify(mappedModuleName, null, 6) // using 6 because of misalignment when nested below + .slice(0, -1) + ' '.repeat(4) + }]` /// align last bracket correctly as well + : mappedModuleName; + const error = new Error( + _chalk().default.red(`${_chalk().default.bold('Configuration error')}: + +Could not locate module ${_chalk().default.bold(moduleName)} mapped as: +${_chalk().default.bold(mappedAs)}. + +Please check your configuration for these entries: +{ + "moduleNameMapper": { + "${regex.toString()}": "${_chalk().default.bold(original)}" + }, + "resolver": ${_chalk().default.bold(String(resolver))} +}`) + ); + error.name = ''; + return error; +}; +function loadResolver(resolver) { + if (resolver == null) { + return _defaultResolver.default; + } + const loadedResolver = require(resolver); + if (loadedResolver == null) { + throw new Error(`Resolver located at ${resolver} does not export anything`); + } + if (typeof loadedResolver === 'function') { + return loadedResolver; + } + if ( + typeof loadedResolver === 'object' && + (loadedResolver.sync != null || loadedResolver.async != null) + ) { + return loadedResolver; + } + throw new Error( + `Resolver located at ${resolver} does not export a function or an object with "sync" and "async" props` + ); +} diff --git a/node_modules/jest-resolve/build/shouldLoadAsEsm.js b/node_modules/jest-resolve/build/shouldLoadAsEsm.js new file mode 100644 index 0000000..ce2efc4 --- /dev/null +++ b/node_modules/jest-resolve/build/shouldLoadAsEsm.js @@ -0,0 +1,90 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.clearCachedLookups = clearCachedLookups; +exports.default = cachedShouldLoadAsEsm; +function _path() { + const data = require('path'); + _path = function () { + return data; + }; + return data; +} +function _vm() { + const data = require('vm'); + _vm = function () { + return data; + }; + return data; +} +var _fileWalkers = require('./fileWalkers'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// @ts-expect-error: experimental, not added to the types + +const runtimeSupportsVmModules = typeof _vm().SyntheticModule === 'function'; +const cachedFileLookups = new Map(); +const cachedDirLookups = new Map(); +const cachedChecks = new Map(); +function clearCachedLookups() { + cachedFileLookups.clear(); + cachedDirLookups.clear(); + cachedChecks.clear(); +} +function cachedShouldLoadAsEsm(path, extensionsToTreatAsEsm) { + if (!runtimeSupportsVmModules) { + return false; + } + let cachedLookup = cachedFileLookups.get(path); + if (cachedLookup === undefined) { + cachedLookup = shouldLoadAsEsm(path, extensionsToTreatAsEsm); + cachedFileLookups.set(path, cachedLookup); + } + return cachedLookup; +} + +// this is a bad version of what https://github.com/nodejs/modules/issues/393 would provide +function shouldLoadAsEsm(path, extensionsToTreatAsEsm) { + const extension = (0, _path().extname)(path); + if (extension === '.mjs') { + return true; + } + if (extension === '.cjs') { + return false; + } + if (extension !== '.js') { + return extensionsToTreatAsEsm.includes(extension); + } + const cwd = (0, _path().dirname)(path); + let cachedLookup = cachedDirLookups.get(cwd); + if (cachedLookup === undefined) { + cachedLookup = cachedPkgCheck(cwd); + cachedFileLookups.set(cwd, cachedLookup); + } + return cachedLookup; +} +function cachedPkgCheck(cwd) { + const pkgPath = (0, _fileWalkers.findClosestPackageJson)(cwd); + if (!pkgPath) { + return false; + } + let hasModuleField = cachedChecks.get(pkgPath); + if (hasModuleField != null) { + return hasModuleField; + } + try { + const pkg = (0, _fileWalkers.readPackageCached)(pkgPath); + hasModuleField = pkg.type === 'module'; + } catch { + hasModuleField = false; + } + cachedChecks.set(pkgPath, hasModuleField); + return hasModuleField; +} diff --git a/node_modules/jest-resolve/build/types.js b/node_modules/jest-resolve/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-resolve/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-resolve/build/utils.js b/node_modules/jest-resolve/build/utils.js new file mode 100644 index 0000000..8a7fd04 --- /dev/null +++ b/node_modules/jest-resolve/build/utils.js @@ -0,0 +1,233 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.resolveWatchPlugin = + exports.resolveTestEnvironment = + exports.resolveSequencer = + exports.resolveRunner = + void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestValidate() { + const data = require('jest-validate'); + _jestValidate = function () { + return data; + }; + return data; +} +var _resolver = _interopRequireDefault(require('./resolver')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const BULLET = _chalk().default.bold('\u25cf '); +const DOCUMENTATION_NOTE = ` ${_chalk().default.bold( + 'Configuration Documentation:' +)} + https://jestjs.io/docs/configuration +`; +const createValidationError = message => + new (_jestValidate().ValidationError)( + `${BULLET}Validation Error`, + message, + DOCUMENTATION_NOTE + ); +const replaceRootDirInPath = (rootDir, filePath) => { + if (!/^/.test(filePath)) { + return filePath; + } + return path().resolve( + rootDir, + path().normalize(`./${filePath.substr(''.length)}`) + ); +}; +const resolveWithPrefix = ( + resolver, + { + filePath, + humanOptionName, + optionName, + prefix, + requireResolveFunction, + rootDir + } +) => { + const fileName = replaceRootDirInPath(rootDir, filePath); + let module = _resolver.default.findNodeModule(`${prefix}${fileName}`, { + basedir: rootDir, + resolver: resolver || undefined + }); + if (module) { + return module; + } + try { + return requireResolveFunction(`${prefix}${fileName}`); + } catch {} + module = _resolver.default.findNodeModule(fileName, { + basedir: rootDir, + resolver: resolver || undefined + }); + if (module) { + return module; + } + try { + return requireResolveFunction(fileName); + } catch {} + throw createValidationError( + ` ${humanOptionName} ${_chalk().default.bold( + fileName + )} cannot be found. Make sure the ${_chalk().default.bold( + optionName + )} configuration option points to an existing node module.` + ); +}; + +/** + * Finds the test environment to use: + * + * 1. looks for jest-environment- relative to project. + * 1. looks for jest-environment- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ +const resolveTestEnvironment = ({ + rootDir, + testEnvironment: filePath, + requireResolveFunction +}) => { + // we don't want to resolve the actual `jsdom` module if `jest-environment-jsdom` is not installed, but `jsdom` package is + if (filePath === 'jsdom') { + filePath = 'jest-environment-jsdom'; + } + try { + return resolveWithPrefix(undefined, { + filePath, + humanOptionName: 'Test environment', + optionName: 'testEnvironment', + prefix: 'jest-environment-', + requireResolveFunction, + rootDir + }); + } catch (error) { + if (filePath === 'jest-environment-jsdom') { + error.message += + '\n\nAs of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately.'; + } + throw error; + } +}; + +/** + * Finds the watch plugins to use: + * + * 1. looks for jest-watch- relative to project. + * 1. looks for jest-watch- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ +exports.resolveTestEnvironment = resolveTestEnvironment; +const resolveWatchPlugin = ( + resolver, + {filePath, rootDir, requireResolveFunction} +) => + resolveWithPrefix(resolver, { + filePath, + humanOptionName: 'Watch plugin', + optionName: 'watchPlugins', + prefix: 'jest-watch-', + requireResolveFunction, + rootDir + }); + +/** + * Finds the runner to use: + * + * 1. looks for jest-runner- relative to project. + * 1. looks for jest-runner- relative to Jest. + * 1. looks for relative to project. + * 1. looks for relative to Jest. + */ +exports.resolveWatchPlugin = resolveWatchPlugin; +const resolveRunner = (resolver, {filePath, rootDir, requireResolveFunction}) => + resolveWithPrefix(resolver, { + filePath, + humanOptionName: 'Jest Runner', + optionName: 'runner', + prefix: 'jest-runner-', + requireResolveFunction, + rootDir + }); +exports.resolveRunner = resolveRunner; +const resolveSequencer = ( + resolver, + {filePath, rootDir, requireResolveFunction} +) => + resolveWithPrefix(resolver, { + filePath, + humanOptionName: 'Jest Sequencer', + optionName: 'testSequencer', + prefix: 'jest-sequencer-', + requireResolveFunction, + rootDir + }); +exports.resolveSequencer = resolveSequencer; diff --git a/node_modules/jest-resolve/package.json b/node_modules/jest-resolve/package.json new file mode 100644 index 0000000..6e41828 --- /dev/null +++ b/node_modules/jest-resolve/package.json @@ -0,0 +1,44 @@ +{ + "name": "jest-resolve", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-resolve" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "chalk": "^4.0.0", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.2.1", + "jest-pnp-resolver": "^1.2.2", + "jest-util": "^29.2.1", + "jest-validate": "^29.2.2", + "resolve": "^1.20.0", + "resolve.exports": "^1.1.0", + "slash": "^3.0.0" + }, + "devDependencies": { + "@tsd/typescript": "~4.8.2", + "@types/graceful-fs": "^4.1.3", + "@types/pnpapi": "^0.0.2", + "@types/resolve": "^1.20.2", + "tsd-lite": "^0.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-runner/LICENSE b/node_modules/jest-runner/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-runner/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-runner/build/index.d.ts b/node_modules/jest-runner/build/index.d.ts new file mode 100644 index 0000000..561f032 --- /dev/null +++ b/node_modules/jest-runner/build/index.d.ts @@ -0,0 +1,127 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import {Config} from '@jest/types'; +import type {SerializableError} from '@jest/test-result'; +import {Test} from '@jest/test-result'; +import {TestEvents} from '@jest/test-result'; +import type {TestResult} from '@jest/test-result'; +import {TestWatcher} from 'jest-watcher'; + +declare abstract class BaseTestRunner { + protected readonly _globalConfig: Config.GlobalConfig; + protected readonly _context: TestRunnerContext; + readonly isSerial?: boolean; + abstract readonly supportsEventEmitters: boolean; + constructor(_globalConfig: Config.GlobalConfig, _context: TestRunnerContext); +} + +export declare abstract class CallbackTestRunner + extends BaseTestRunner + implements CallbackTestRunnerInterface +{ + readonly supportsEventEmitters = false; + abstract runTests( + tests: Array, + watcher: TestWatcher, + onStart: OnTestStart, + onResult: OnTestSuccess, + onFailure: OnTestFailure, + options: TestRunnerOptions, + ): Promise; +} + +export declare interface CallbackTestRunnerInterface { + readonly isSerial?: boolean; + readonly supportsEventEmitters?: boolean; + runTests( + tests: Array, + watcher: TestWatcher, + onStart: OnTestStart, + onResult: OnTestSuccess, + onFailure: OnTestFailure, + options: TestRunnerOptions, + ): Promise; +} + +export {Config}; + +export declare abstract class EmittingTestRunner + extends BaseTestRunner + implements EmittingTestRunnerInterface +{ + readonly supportsEventEmitters = true; + abstract runTests( + tests: Array, + watcher: TestWatcher, + options: TestRunnerOptions, + ): Promise; + abstract on( + eventName: Name, + listener: (eventData: TestEvents[Name]) => void | Promise, + ): UnsubscribeFn; +} + +export declare interface EmittingTestRunnerInterface { + readonly isSerial?: boolean; + readonly supportsEventEmitters: true; + runTests( + tests: Array, + watcher: TestWatcher, + options: TestRunnerOptions, + ): Promise; + on( + eventName: Name, + listener: (eventData: TestEvents[Name]) => void | Promise, + ): UnsubscribeFn; +} + +export declare type JestTestRunner = CallbackTestRunner | EmittingTestRunner; + +export declare type OnTestFailure = ( + test: Test, + serializableError: SerializableError, +) => Promise; + +export declare type OnTestStart = (test: Test) => Promise; + +export declare type OnTestSuccess = ( + test: Test, + testResult: TestResult, +) => Promise; + +export {Test}; + +export {TestEvents}; + +declare class TestRunner extends EmittingTestRunner { + #private; + runTests( + tests: Array, + watcher: TestWatcher, + options: TestRunnerOptions, + ): Promise; + on( + eventName: Name, + listener: (eventData: TestEvents[Name]) => void | Promise, + ): UnsubscribeFn; +} +export default TestRunner; + +export declare type TestRunnerContext = { + changedFiles?: Set; + sourcesRelatedToTestsInChangedFiles?: Set; +}; + +export declare type TestRunnerOptions = { + serial: boolean; +}; + +export {TestWatcher}; + +export declare type UnsubscribeFn = () => void; + +export {}; diff --git a/node_modules/jest-runner/build/index.js b/node_modules/jest-runner/build/index.js new file mode 100644 index 0000000..de46543 --- /dev/null +++ b/node_modules/jest-runner/build/index.js @@ -0,0 +1,218 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'CallbackTestRunner', { + enumerable: true, + get: function () { + return _types.CallbackTestRunner; + } +}); +Object.defineProperty(exports, 'EmittingTestRunner', { + enumerable: true, + get: function () { + return _types.EmittingTestRunner; + } +}); +exports.default = void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _emittery() { + const data = _interopRequireDefault(require('emittery')); + _emittery = function () { + return data; + }; + return data; +} +function _pLimit() { + const data = _interopRequireDefault(require('p-limit')); + _pLimit = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _jestWorker() { + const data = require('jest-worker'); + _jestWorker = function () { + return data; + }; + return data; +} +var _runTest = _interopRequireDefault(require('./runTest')); +var _types = require('./types'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class TestRunner extends _types.EmittingTestRunner { + #eventEmitter = new (_emittery().default)(); + async runTests(tests, watcher, options) { + return options.serial + ? this.#createInBandTestRun(tests, watcher) + : this.#createParallelTestRun(tests, watcher); + } + async #createInBandTestRun(tests, watcher) { + process.env.JEST_WORKER_ID = '1'; + const mutex = (0, _pLimit().default)(1); + return tests.reduce( + (promise, test) => + mutex(() => + promise + .then(async () => { + if (watcher.isInterrupted()) { + throw new CancelRun(); + } + + // `deepCyclicCopy` used here to avoid mem-leak + const sendMessageToJest = (eventName, args) => + this.#eventEmitter.emit( + eventName, + (0, _jestUtil().deepCyclicCopy)(args, { + keepPrototype: false + }) + ); + await this.#eventEmitter.emit('test-file-start', [test]); + return (0, _runTest.default)( + test.path, + this._globalConfig, + test.context.config, + test.context.resolver, + this._context, + sendMessageToJest + ); + }) + .then( + result => + this.#eventEmitter.emit('test-file-success', [test, result]), + error => + this.#eventEmitter.emit('test-file-failure', [test, error]) + ) + ), + Promise.resolve() + ); + } + async #createParallelTestRun(tests, watcher) { + const resolvers = new Map(); + for (const test of tests) { + if (!resolvers.has(test.context.config.id)) { + resolvers.set(test.context.config.id, { + config: test.context.config, + serializableModuleMap: test.context.moduleMap.toJSON() + }); + } + } + const worker = new (_jestWorker().Worker)(require.resolve('./testWorker'), { + exposedMethods: ['worker'], + forkOptions: { + serialization: 'json', + stdio: 'pipe' + }, + // The workerIdleMemoryLimit should've been converted to a number during + // the normalization phase. + idleMemoryLimit: + typeof this._globalConfig.workerIdleMemoryLimit === 'number' + ? this._globalConfig.workerIdleMemoryLimit + : undefined, + maxRetries: 3, + numWorkers: this._globalConfig.maxWorkers, + setupArgs: [ + { + serializableResolvers: Array.from(resolvers.values()) + } + ] + }); + if (worker.getStdout()) worker.getStdout().pipe(process.stdout); + if (worker.getStderr()) worker.getStderr().pipe(process.stderr); + const mutex = (0, _pLimit().default)(this._globalConfig.maxWorkers); + + // Send test suites to workers continuously instead of all at once to track + // the start time of individual tests. + const runTestInWorker = test => + mutex(async () => { + if (watcher.isInterrupted()) { + return Promise.reject(); + } + await this.#eventEmitter.emit('test-file-start', [test]); + const promise = worker.worker({ + config: test.context.config, + context: { + ...this._context, + changedFiles: + this._context.changedFiles && + Array.from(this._context.changedFiles), + sourcesRelatedToTestsInChangedFiles: + this._context.sourcesRelatedToTestsInChangedFiles && + Array.from(this._context.sourcesRelatedToTestsInChangedFiles) + }, + globalConfig: this._globalConfig, + path: test.path + }); + if (promise.UNSTABLE_onCustomMessage) { + // TODO: Get appropriate type for `onCustomMessage` + promise.UNSTABLE_onCustomMessage(([event, payload]) => + this.#eventEmitter.emit(event, payload) + ); + } + return promise; + }); + const onInterrupt = new Promise((_, reject) => { + watcher.on('change', state => { + if (state.interrupted) { + reject(new CancelRun()); + } + }); + }); + const runAllTests = Promise.all( + tests.map(test => + runTestInWorker(test).then( + result => + this.#eventEmitter.emit('test-file-success', [test, result]), + error => this.#eventEmitter.emit('test-file-failure', [test, error]) + ) + ) + ); + const cleanup = async () => { + const {forceExited} = await worker.end(); + if (forceExited) { + console.error( + _chalk().default.yellow( + 'A worker process has failed to exit gracefully and has been force exited. ' + + 'This is likely caused by tests leaking due to improper teardown. ' + + 'Try running with --detectOpenHandles to find leaks. ' + + 'Active timers can also cause this, ensure that .unref() was called on them.' + ) + ); + } + }; + return Promise.race([runAllTests, onInterrupt]).then(cleanup, cleanup); + } + on(eventName, listener) { + return this.#eventEmitter.on(eventName, listener); + } +} +exports.default = TestRunner; +class CancelRun extends Error { + constructor(message) { + super(message); + this.name = 'CancelRun'; + } +} diff --git a/node_modules/jest-runner/build/runTest.js b/node_modules/jest-runner/build/runTest.js new file mode 100644 index 0000000..9901f2f --- /dev/null +++ b/node_modules/jest-runner/build/runTest.js @@ -0,0 +1,462 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = runTest; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _sourceMapSupport() { + const data = _interopRequireDefault(require('source-map-support')); + _sourceMapSupport = function () { + return data; + }; + return data; +} +function _console() { + const data = require('@jest/console'); + _console = function () { + return data; + }; + return data; +} +function _transform() { + const data = require('@jest/transform'); + _transform = function () { + return data; + }; + return data; +} +function docblock() { + const data = _interopRequireWildcard(require('jest-docblock')); + docblock = function () { + return data; + }; + return data; +} +function _jestLeakDetector() { + const data = _interopRequireDefault(require('jest-leak-detector')); + _jestLeakDetector = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +function _jestResolve() { + const data = require('jest-resolve'); + _jestResolve = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +function freezeConsole(testConsole, config) { + // @ts-expect-error: `_log` is `private` - we should figure out some proper API here + testConsole._log = function fakeConsolePush(_type, message) { + const error = new (_jestUtil().ErrorWithStack)( + `${_chalk().default.red( + `${_chalk().default.bold( + 'Cannot log after tests are done.' + )} Did you forget to wait for something async in your test?` + )}\nAttempted to log "${message}".`, + fakeConsolePush + ); + const formattedError = (0, _jestMessageUtil().formatExecError)( + error, + config, + { + noStackTrace: false + }, + undefined, + true + ); + process.stderr.write(`\n${formattedError}\n`); + process.exitCode = 1; + }; +} + +// Keeping the core of "runTest" as a separate function (as "runTestInternal") +// is key to be able to detect memory leaks. Since all variables are local to +// the function, when "runTestInternal" finishes its execution, they can all be +// freed, UNLESS something else is leaking them (and that's why we can detect +// the leak!). +// +// If we had all the code in a single function, we should manually nullify all +// references to verify if there is a leak, which is not maintainable and error +// prone. That's why "runTestInternal" CANNOT be inlined inside "runTest". +async function runTestInternal( + path, + globalConfig, + projectConfig, + resolver, + context, + sendMessageToJest +) { + const testSource = fs().readFileSync(path, 'utf8'); + const docblockPragmas = docblock().parse(docblock().extract(testSource)); + const customEnvironment = docblockPragmas['jest-environment']; + let testEnvironment = projectConfig.testEnvironment; + if (customEnvironment) { + if (Array.isArray(customEnvironment)) { + throw new Error( + `You can only define a single test environment through docblocks, got "${customEnvironment.join( + ', ' + )}"` + ); + } + testEnvironment = (0, _jestResolve().resolveTestEnvironment)({ + ...projectConfig, + requireResolveFunction: require.resolve, + testEnvironment: customEnvironment + }); + } + const cacheFS = new Map([[path, testSource]]); + const transformer = await (0, _transform().createScriptTransformer)( + projectConfig, + cacheFS + ); + const TestEnvironment = await transformer.requireAndTranspileModule( + testEnvironment + ); + const testFramework = await transformer.requireAndTranspileModule( + process.env.JEST_JASMINE === '1' + ? require.resolve('jest-jasmine2') + : projectConfig.testRunner + ); + const Runtime = (0, _jestUtil().interopRequireDefault)( + projectConfig.runtime + ? require(projectConfig.runtime) + : require('jest-runtime') + ).default; + const consoleOut = globalConfig.useStderr ? process.stderr : process.stdout; + const consoleFormatter = (type, message) => + (0, _console().getConsoleOutput)( + // 4 = the console call is buried 4 stack frames deep + _console().BufferedConsole.write([], type, message, 4), + projectConfig, + globalConfig + ); + let testConsole; + if (globalConfig.silent) { + testConsole = new (_console().NullConsole)( + consoleOut, + consoleOut, + consoleFormatter + ); + } else if (globalConfig.verbose) { + testConsole = new (_console().CustomConsole)( + consoleOut, + consoleOut, + consoleFormatter + ); + } else { + testConsole = new (_console().BufferedConsole)(); + } + let extraTestEnvironmentOptions; + const docblockEnvironmentOptions = + docblockPragmas['jest-environment-options']; + if (typeof docblockEnvironmentOptions === 'string') { + extraTestEnvironmentOptions = JSON.parse(docblockEnvironmentOptions); + } + const environment = new TestEnvironment( + { + globalConfig, + projectConfig: extraTestEnvironmentOptions + ? { + ...projectConfig, + testEnvironmentOptions: { + ...projectConfig.testEnvironmentOptions, + ...extraTestEnvironmentOptions + } + } + : projectConfig + }, + { + console: testConsole, + docblockPragmas, + testPath: path + } + ); + if (typeof environment.getVmContext !== 'function') { + console.error( + `Test environment found at "${testEnvironment}" does not export a "getVmContext" method, which is mandatory from Jest 27. This method is a replacement for "runScript".` + ); + process.exit(1); + } + const leakDetector = projectConfig.detectLeaks + ? new (_jestLeakDetector().default)(environment) + : null; + (0, _jestUtil().setGlobal)(environment.global, 'console', testConsole); + const runtime = new Runtime( + projectConfig, + environment, + resolver, + transformer, + cacheFS, + { + changedFiles: context.changedFiles, + collectCoverage: globalConfig.collectCoverage, + collectCoverageFrom: globalConfig.collectCoverageFrom, + coverageProvider: globalConfig.coverageProvider, + sourcesRelatedToTestsInChangedFiles: + context.sourcesRelatedToTestsInChangedFiles + }, + path, + globalConfig + ); + let isTornDown = false; + const tearDownEnv = async () => { + if (!isTornDown) { + runtime.teardown(); + await environment.teardown(); + isTornDown = true; + } + }; + const start = Date.now(); + for (const path of projectConfig.setupFiles) { + const esm = runtime.unstable_shouldLoadAsEsm(path); + if (esm) { + await runtime.unstable_importModule(path); + } else { + const setupFile = runtime.requireModule(path); + if (typeof setupFile === 'function') { + await setupFile(); + } + } + } + const sourcemapOptions = { + environment: 'node', + handleUncaughtExceptions: false, + retrieveSourceMap: source => { + const sourceMapSource = runtime.getSourceMaps()?.get(source); + if (sourceMapSource) { + try { + return { + map: JSON.parse(fs().readFileSync(sourceMapSource, 'utf8')), + url: source + }; + } catch {} + } + return null; + } + }; + + // For tests + runtime + .requireInternalModule(require.resolve('source-map-support')) + .install(sourcemapOptions); + + // For runtime errors + _sourceMapSupport().default.install(sourcemapOptions); + if ( + environment.global && + environment.global.process && + environment.global.process.exit + ) { + const realExit = environment.global.process.exit; + environment.global.process.exit = function exit(...args) { + const error = new (_jestUtil().ErrorWithStack)( + `process.exit called with "${args.join(', ')}"`, + exit + ); + const formattedError = (0, _jestMessageUtil().formatExecError)( + error, + projectConfig, + { + noStackTrace: false + }, + undefined, + true + ); + process.stderr.write(formattedError); + return realExit(...args); + }; + } + + // if we don't have `getVmContext` on the env skip coverage + const collectV8Coverage = + globalConfig.collectCoverage && + globalConfig.coverageProvider === 'v8' && + typeof environment.getVmContext === 'function'; + + // Node's error-message stack size is limited at 10, but it's pretty useful + // to see more than that when a test fails. + Error.stackTraceLimit = 100; + try { + await environment.setup(); + let result; + try { + if (collectV8Coverage) { + await runtime.collectV8Coverage(); + } + result = await testFramework( + globalConfig, + projectConfig, + environment, + runtime, + path, + sendMessageToJest + ); + } catch (err) { + // Access stack before uninstalling sourcemaps + err.stack; + throw err; + } finally { + if (collectV8Coverage) { + await runtime.stopCollectingV8Coverage(); + } + } + freezeConsole(testConsole, projectConfig); + const testCount = + result.numPassingTests + + result.numFailingTests + + result.numPendingTests + + result.numTodoTests; + const end = Date.now(); + const testRuntime = end - start; + result.perfStats = { + end, + runtime: testRuntime, + slow: testRuntime / 1000 > projectConfig.slowTestThreshold, + start + }; + result.testFilePath = path; + result.console = testConsole.getBuffer(); + result.skipped = testCount === result.numPendingTests; + result.displayName = projectConfig.displayName; + const coverage = runtime.getAllCoverageInfoCopy(); + if (coverage) { + const coverageKeys = Object.keys(coverage); + if (coverageKeys.length) { + result.coverage = coverage; + } + } + if (collectV8Coverage) { + const v8Coverage = runtime.getAllV8CoverageInfoCopy(); + if (v8Coverage && v8Coverage.length > 0) { + result.v8Coverage = v8Coverage; + } + } + if (globalConfig.logHeapUsage) { + // @ts-expect-error - doesn't exist on globalThis + globalThis.gc?.(); + result.memoryUsage = process.memoryUsage().heapUsed; + } + await tearDownEnv(); + + // Delay the resolution to allow log messages to be output. + return await new Promise(resolve => { + setImmediate(() => + resolve({ + leakDetector, + result + }) + ); + }); + } finally { + await tearDownEnv(); + _sourceMapSupport().default.resetRetrieveHandlers(); + } +} +async function runTest( + path, + globalConfig, + config, + resolver, + context, + sendMessageToJest +) { + const {leakDetector, result} = await runTestInternal( + path, + globalConfig, + config, + resolver, + context, + sendMessageToJest + ); + if (leakDetector) { + // We wanna allow a tiny but time to pass to allow last-minute cleanup + await new Promise(resolve => setTimeout(resolve, 100)); + + // Resolve leak detector, outside the "runTestInternal" closure. + result.leaks = await leakDetector.isLeaking(); + } else { + result.leaks = false; + } + return result; +} diff --git a/node_modules/jest-runner/build/testWorker.js b/node_modules/jest-runner/build/testWorker.js new file mode 100644 index 0000000..39292ea --- /dev/null +++ b/node_modules/jest-runner/build/testWorker.js @@ -0,0 +1,123 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.setup = setup; +exports.worker = worker; +function _exit() { + const data = _interopRequireDefault(require('exit')); + _exit = function () { + return data; + }; + return data; +} +function _jestHasteMap() { + const data = _interopRequireDefault(require('jest-haste-map')); + _jestHasteMap = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +function _jestRuntime() { + const data = _interopRequireDefault(require('jest-runtime')); + _jestRuntime = function () { + return data; + }; + return data; +} +function _jestWorker() { + const data = require('jest-worker'); + _jestWorker = function () { + return data; + }; + return data; +} +var _runTest = _interopRequireDefault(require('./runTest')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + */ + +// Make sure uncaught errors are logged before we exit. +process.on('uncaughtException', err => { + console.error(err.stack); + (0, _exit().default)(1); +}); +const formatError = error => { + if (typeof error === 'string') { + const {message, stack} = (0, _jestMessageUtil().separateMessageFromStack)( + error + ); + return { + message, + stack, + type: 'Error' + }; + } + return { + code: error.code || undefined, + message: error.message, + stack: error.stack, + type: 'Error' + }; +}; +const resolvers = new Map(); +const getResolver = config => { + const resolver = resolvers.get(config.id); + if (!resolver) { + throw new Error(`Cannot find resolver for: ${config.id}`); + } + return resolver; +}; +function setup(setupData) { + // Module maps that will be needed for the test runs are passed. + for (const { + config, + serializableModuleMap + } of setupData.serializableResolvers) { + const moduleMap = _jestHasteMap() + .default.getStatic(config) + .getModuleMapFromJSON(serializableModuleMap); + resolvers.set( + config.id, + _jestRuntime().default.createResolver(config, moduleMap) + ); + } +} +const sendMessageToJest = (eventName, args) => { + (0, _jestWorker().messageParent)([eventName, args]); +}; +async function worker({config, globalConfig, path, context}) { + try { + return await (0, _runTest.default)( + path, + globalConfig, + config, + getResolver(config), + { + ...context, + changedFiles: context.changedFiles && new Set(context.changedFiles), + sourcesRelatedToTestsInChangedFiles: + context.sourcesRelatedToTestsInChangedFiles && + new Set(context.sourcesRelatedToTestsInChangedFiles) + }, + sendMessageToJest + ); + } catch (error) { + throw formatError(error); + } +} diff --git a/node_modules/jest-runner/build/types.js b/node_modules/jest-runner/build/types.js new file mode 100644 index 0000000..4fe842a --- /dev/null +++ b/node_modules/jest-runner/build/types.js @@ -0,0 +1,29 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.EmittingTestRunner = exports.CallbackTestRunner = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class BaseTestRunner { + isSerial; + supportsEventEmitters; + constructor(_globalConfig, _context) { + this._globalConfig = _globalConfig; + this._context = _context; + } +} +class CallbackTestRunner extends BaseTestRunner { + supportsEventEmitters = false; +} +exports.CallbackTestRunner = CallbackTestRunner; +class EmittingTestRunner extends BaseTestRunner { + supportsEventEmitters = true; +} +exports.EmittingTestRunner = EmittingTestRunner; diff --git a/node_modules/jest-runner/package.json b/node_modules/jest-runner/package.json new file mode 100644 index 0000000..ee9e015 --- /dev/null +++ b/node_modules/jest-runner/package.json @@ -0,0 +1,57 @@ +{ + "name": "jest-runner", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-runner" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/console": "^29.2.1", + "@jest/environment": "^29.2.2", + "@jest/test-result": "^29.2.1", + "@jest/transform": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/node": "*", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "graceful-fs": "^4.2.9", + "jest-docblock": "^29.2.0", + "jest-environment-node": "^29.2.2", + "jest-haste-map": "^29.2.1", + "jest-leak-detector": "^29.2.1", + "jest-message-util": "^29.2.1", + "jest-resolve": "^29.2.2", + "jest-runtime": "^29.2.2", + "jest-util": "^29.2.1", + "jest-watcher": "^29.2.2", + "jest-worker": "^29.2.1", + "p-limit": "^3.1.0", + "source-map-support": "0.5.13" + }, + "devDependencies": { + "@tsd/typescript": "~4.8.2", + "@types/exit": "^0.1.30", + "@types/graceful-fs": "^4.1.3", + "@types/source-map-support": "^0.5.0", + "jest-jasmine2": "^29.2.2", + "tsd-lite": "^0.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-runtime/LICENSE b/node_modules/jest-runtime/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-runtime/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-runtime/build/helpers.js b/node_modules/jest-runtime/build/helpers.js new file mode 100644 index 0000000..71e1561 --- /dev/null +++ b/node_modules/jest-runtime/build/helpers.js @@ -0,0 +1,134 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.findSiblingsWithFileExtension = + exports.decodePossibleOutsideJestVmPath = + exports.createOutsideJestVmPath = + void 0; +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _glob() { + const data = _interopRequireDefault(require('glob')); + _glob = function () { + return data; + }; + return data; +} +function _slash() { + const data = _interopRequireDefault(require('slash')); + _slash = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const OUTSIDE_JEST_VM_PROTOCOL = 'jest-main:'; +// String manipulation is easier here, fileURLToPath is only in newer Nodes, +// plus setting non-standard protocols on URL objects is difficult. +const createOutsideJestVmPath = path => + `${OUTSIDE_JEST_VM_PROTOCOL}//${encodeURIComponent(path)}`; +exports.createOutsideJestVmPath = createOutsideJestVmPath; +const decodePossibleOutsideJestVmPath = outsideJestVmPath => { + if (outsideJestVmPath.startsWith(OUTSIDE_JEST_VM_PROTOCOL)) { + return decodeURIComponent( + outsideJestVmPath.replace( + new RegExp(`^${OUTSIDE_JEST_VM_PROTOCOL}//`), + '' + ) + ); + } + return undefined; +}; +exports.decodePossibleOutsideJestVmPath = decodePossibleOutsideJestVmPath; +const findSiblingsWithFileExtension = ( + moduleFileExtensions, + from, + moduleName +) => { + if (!path().isAbsolute(moduleName) && path().extname(moduleName) === '') { + const dirname = path().dirname(from); + const pathToModule = path().resolve(dirname, moduleName); + try { + const slashedDirname = (0, _slash().default)(dirname); + const matches = _glob() + .default.sync(`${pathToModule}.*`) + .map(match => (0, _slash().default)(match)) + .map(match => { + const relativePath = path().posix.relative(slashedDirname, match); + return path().posix.dirname(match) === slashedDirname + ? `./${relativePath}` + : relativePath; + }) + .map(match => `\t'${match}'`) + .join('\n'); + if (matches) { + const foundMessage = `\n\nHowever, Jest was able to find:\n${matches}`; + const mappedModuleFileExtensions = moduleFileExtensions + .map(ext => `'${ext}'`) + .join(', '); + return ( + `${foundMessage}\n\nYou might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ` + + `[${mappedModuleFileExtensions}].\n\nSee https://jestjs.io/docs/configuration#modulefileextensions-arraystring` + ); + } + } catch {} + } + return ''; +}; +exports.findSiblingsWithFileExtension = findSiblingsWithFileExtension; diff --git a/node_modules/jest-runtime/build/index.d.ts b/node_modules/jest-runtime/build/index.d.ts new file mode 100644 index 0000000..da338c5 --- /dev/null +++ b/node_modules/jest-runtime/build/index.d.ts @@ -0,0 +1,185 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import {CallerTransformOptions} from '@jest/transform'; +import type {Config} from '@jest/types'; +import type {expect} from '@jest/globals'; +import type {Global} from '@jest/types'; +import {IHasteMap} from 'jest-haste-map'; +import {IModuleMap} from 'jest-haste-map'; +import type {JestEnvironment} from '@jest/environment'; +import Resolver from 'jest-resolve'; +import {ScriptTransformer} from '@jest/transform'; +import {shouldInstrument} from '@jest/transform'; +import {ShouldInstrumentOptions} from '@jest/transform'; +import type {SourceMapRegistry} from '@jest/source-map'; +import type {TestContext} from '@jest/test-result'; +import type {V8CoverageResult} from '@jest/test-result'; + +declare type HasteMapOptions = { + console?: Console; + maxWorkers: number; + resetCache: boolean; + watch?: boolean; + watchman: boolean; +}; + +declare interface InternalModuleOptions + extends Required { + isInternalModule: boolean; +} + +declare interface JestGlobals extends Global.TestFrameworkGlobals { + expect: typeof expect; +} + +declare class Runtime { + private readonly _cacheFS; + private readonly _config; + private readonly _globalConfig?; + private readonly _coverageOptions; + private _currentlyExecutingModulePath; + private readonly _environment; + private readonly _explicitShouldMock; + private readonly _explicitShouldMockModule; + private _fakeTimersImplementation; + private readonly _internalModuleRegistry; + private _isCurrentlyExecutingManualMock; + private _mainModule; + private readonly _mockFactories; + private readonly _mockMetaDataCache; + private _mockRegistry; + private _isolatedMockRegistry; + private readonly _moduleMockRegistry; + private readonly _moduleMockFactories; + private readonly _moduleMocker; + private _isolatedModuleRegistry; + private _moduleRegistry; + private readonly _esmoduleRegistry; + private readonly _cjsNamedExports; + private readonly _esmModuleLinkingMap; + private readonly _testPath; + private readonly _resolver; + private _shouldAutoMock; + private readonly _shouldMockModuleCache; + private readonly _shouldUnmockTransitiveDependenciesCache; + private readonly _sourceMapRegistry; + private readonly _scriptTransformer; + private readonly _fileTransforms; + private readonly _fileTransformsMutex; + private _v8CoverageInstrumenter; + private _v8CoverageResult; + private _v8CoverageSources; + private readonly _transitiveShouldMock; + private _unmockList; + private readonly _virtualMocks; + private readonly _virtualModuleMocks; + private _moduleImplementation?; + private readonly jestObjectCaches; + private jestGlobals?; + private readonly esmConditions; + private readonly cjsConditions; + private isTornDown; + constructor( + config: Config.ProjectConfig, + environment: JestEnvironment, + resolver: Resolver, + transformer: ScriptTransformer, + cacheFS: Map, + coverageOptions: ShouldInstrumentOptions, + testPath: string, + globalConfig?: Config.GlobalConfig, + ); + static shouldInstrument: typeof shouldInstrument; + static createContext( + config: Config.ProjectConfig, + options: { + console?: Console; + maxWorkers: number; + watch?: boolean; + watchman: boolean; + }, + ): Promise; + static createHasteMap( + config: Config.ProjectConfig, + options?: HasteMapOptions, + ): Promise; + static createResolver( + config: Config.ProjectConfig, + moduleMap: IModuleMap, + ): Resolver; + static runCLI(): Promise; + static getCLIOptions(): never; + unstable_shouldLoadAsEsm(path: string): boolean; + private loadEsmModule; + private resolveModule; + private linkAndEvaluateModule; + unstable_importModule(from: string, moduleName?: string): Promise; + private loadCjsAsEsm; + private importMock; + private getExportsOfCjs; + requireModule( + from: string, + moduleName?: string, + options?: InternalModuleOptions, + isRequireActual?: boolean, + ): T; + requireInternalModule(from: string, to?: string): T; + requireActual(from: string, moduleName: string): T; + requireMock(from: string, moduleName: string): T; + private _loadModule; + private _getFullTransformationOptions; + requireModuleOrMock(from: string, moduleName: string): T; + isolateModules(fn: () => void): void; + resetModules(): void; + collectV8Coverage(): Promise; + stopCollectingV8Coverage(): Promise; + getAllCoverageInfoCopy(): JestEnvironment['global']['__coverage__']; + getAllV8CoverageInfoCopy(): V8CoverageResult; + getSourceMaps(): SourceMapRegistry; + setMock( + from: string, + moduleName: string, + mockFactory: () => unknown, + options?: { + virtual?: boolean; + }, + ): void; + private setModuleMock; + restoreAllMocks(): void; + resetAllMocks(): void; + clearAllMocks(): void; + teardown(): void; + private _resolveCjsModule; + private _resolveModule; + private _requireResolve; + private _requireResolvePaths; + private _execModule; + private transformFile; + private transformFileAsync; + private createScriptFromCode; + private _requireCoreModule; + private _importCoreModule; + private _getMockedNativeModule; + private _generateMock; + private _shouldMockCjs; + private _shouldMockModule; + private _createRequireImplementation; + private _createJestObjectFor; + private _logFormattedReferenceError; + private wrapCodeInModuleWrapper; + private constructModuleWrapperStart; + private constructInjectedModuleParameters; + private handleExecutionError; + private getGlobalsForCjs; + private getGlobalsForEsm; + private getGlobalsFromEnvironment; + private readFile; + setGlobalsForRuntime(globals: JestGlobals): void; +} +export default Runtime; + +export {}; diff --git a/node_modules/jest-runtime/build/index.js b/node_modules/jest-runtime/build/index.js new file mode 100644 index 0000000..ca4006c --- /dev/null +++ b/node_modules/jest-runtime/build/index.js @@ -0,0 +1,2106 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _module() { + const data = _interopRequireDefault(require('module')); + _module = function () { + return data; + }; + return data; +} +function path() { + const data = _interopRequireWildcard(require('path')); + path = function () { + return data; + }; + return data; +} +function _url() { + const data = require('url'); + _url = function () { + return data; + }; + return data; +} +function _vm() { + const data = require('vm'); + _vm = function () { + return data; + }; + return data; +} +function _cjsModuleLexer() { + const data = require('cjs-module-lexer'); + _cjsModuleLexer = function () { + return data; + }; + return data; +} +function _collectV8Coverage() { + const data = require('collect-v8-coverage'); + _collectV8Coverage = function () { + return data; + }; + return data; +} +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _slash() { + const data = _interopRequireDefault(require('slash')); + _slash = function () { + return data; + }; + return data; +} +function _stripBom() { + const data = _interopRequireDefault(require('strip-bom')); + _stripBom = function () { + return data; + }; + return data; +} +function _transform() { + const data = require('@jest/transform'); + _transform = function () { + return data; + }; + return data; +} +function _jestHasteMap() { + const data = _interopRequireDefault(require('jest-haste-map')); + _jestHasteMap = function () { + return data; + }; + return data; +} +function _jestMessageUtil() { + const data = require('jest-message-util'); + _jestMessageUtil = function () { + return data; + }; + return data; +} +function _jestRegexUtil() { + const data = require('jest-regex-util'); + _jestRegexUtil = function () { + return data; + }; + return data; +} +function _jestResolve() { + const data = _interopRequireDefault(require('jest-resolve')); + _jestResolve = function () { + return data; + }; + return data; +} +function _jestSnapshot() { + const data = require('jest-snapshot'); + _jestSnapshot = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _helpers = require('./helpers'); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const esmIsAvailable = typeof _vm().SourceTextModule === 'function'; +const dataURIRegex = + /^data:(?text\/javascript|application\/json|application\/wasm)(?:;(?charset=utf-8|base64))?,(?.*)$/; +const defaultTransformOptions = { + isInternalModule: false, + supportsDynamicImport: esmIsAvailable, + supportsExportNamespaceFrom: false, + supportsStaticESM: false, + supportsTopLevelAwait: false +}; +// These are modules that we know +// * are safe to require from the outside (not stateful, not prone to errors passing in instances from different realms), and +// * take sufficiently long to require to warrant an optimization. +// When required from the outside, they use the worker's require cache and are thus +// only loaded once per worker, not once per test file. +// Use /benchmarks/test-file-overhead to measure the impact. +// Note that this only applies when they are required in an internal context; +// users who require one of these modules in their tests will still get the module from inside the VM. +// Prefer listing a module here only if it is impractical to use the jest-resolve-outside-vm-option where it is required, +// e.g. because there are many require sites spread across the dependency graph. +const INTERNAL_MODULE_REQUIRE_OUTSIDE_OPTIMIZED_MODULES = new Set(['chalk']); +const JEST_RESOLVE_OUTSIDE_VM_OPTION = Symbol.for( + 'jest-resolve-outside-vm-option' +); +const testTimeoutSymbol = Symbol.for('TEST_TIMEOUT_SYMBOL'); +const retryTimesSymbol = Symbol.for('RETRY_TIMES'); +const logErrorsBeforeRetrySymbol = Symbol.for('LOG_ERRORS_BEFORE_RETRY'); +const NODE_MODULES = `${path().sep}node_modules${path().sep}`; +const getModuleNameMapper = config => { + if ( + Array.isArray(config.moduleNameMapper) && + config.moduleNameMapper.length + ) { + return config.moduleNameMapper.map(([regex, moduleName]) => ({ + moduleName, + regex: new RegExp(regex) + })); + } + return null; +}; +const unmockRegExpCache = new WeakMap(); +const EVAL_RESULT_VARIABLE = 'Object.'; +const runtimeSupportsVmModules = typeof _vm().SyntheticModule === 'function'; +const supportsNodeColonModulePrefixInRequire = (() => { + try { + require('node:fs'); + return true; + } catch { + return false; + } +})(); +class Runtime { + _cacheFS; + _config; + _globalConfig; + _coverageOptions; + _currentlyExecutingModulePath; + _environment; + _explicitShouldMock; + _explicitShouldMockModule; + _fakeTimersImplementation; + _internalModuleRegistry; + _isCurrentlyExecutingManualMock; + _mainModule; + _mockFactories; + _mockMetaDataCache; + _mockRegistry; + _isolatedMockRegistry; + _moduleMockRegistry; + _moduleMockFactories; + _moduleMocker; + _isolatedModuleRegistry; + _moduleRegistry; + _esmoduleRegistry; + _cjsNamedExports; + _esmModuleLinkingMap; + _testPath; + _resolver; + _shouldAutoMock; + _shouldMockModuleCache; + _shouldUnmockTransitiveDependenciesCache; + _sourceMapRegistry; + _scriptTransformer; + _fileTransforms; + _fileTransformsMutex; + _v8CoverageInstrumenter; + _v8CoverageResult; + _v8CoverageSources; + _transitiveShouldMock; + _unmockList; + _virtualMocks; + _virtualModuleMocks; + _moduleImplementation; + jestObjectCaches; + jestGlobals; + esmConditions; + cjsConditions; + isTornDown = false; + constructor( + config, + environment, + resolver, + transformer, + cacheFS, + coverageOptions, + testPath, + // TODO: make mandatory in Jest 30 + globalConfig + ) { + this._cacheFS = cacheFS; + this._config = config; + this._coverageOptions = coverageOptions; + this._currentlyExecutingModulePath = ''; + this._environment = environment; + this._globalConfig = globalConfig; + this._explicitShouldMock = new Map(); + this._explicitShouldMockModule = new Map(); + this._internalModuleRegistry = new Map(); + this._isCurrentlyExecutingManualMock = null; + this._mainModule = null; + this._mockFactories = new Map(); + this._mockRegistry = new Map(); + this._moduleMockRegistry = new Map(); + this._moduleMockFactories = new Map(); + invariant( + this._environment.moduleMocker, + '`moduleMocker` must be set on an environment when created' + ); + this._moduleMocker = this._environment.moduleMocker; + this._isolatedModuleRegistry = null; + this._isolatedMockRegistry = null; + this._moduleRegistry = new Map(); + this._esmoduleRegistry = new Map(); + this._cjsNamedExports = new Map(); + this._esmModuleLinkingMap = new WeakMap(); + this._testPath = testPath; + this._resolver = resolver; + this._scriptTransformer = transformer; + this._shouldAutoMock = config.automock; + this._sourceMapRegistry = new Map(); + this._fileTransforms = new Map(); + this._fileTransformsMutex = new Map(); + this._virtualMocks = new Map(); + this._virtualModuleMocks = new Map(); + this.jestObjectCaches = new Map(); + this._mockMetaDataCache = new Map(); + this._shouldMockModuleCache = new Map(); + this._shouldUnmockTransitiveDependenciesCache = new Map(); + this._transitiveShouldMock = new Map(); + this._fakeTimersImplementation = config.fakeTimers.legacyFakeTimers + ? this._environment.fakeTimers + : this._environment.fakeTimersModern; + this._unmockList = unmockRegExpCache.get(config); + if (!this._unmockList && config.unmockedModulePathPatterns) { + this._unmockList = new RegExp( + config.unmockedModulePathPatterns.join('|') + ); + unmockRegExpCache.set(config, this._unmockList); + } + const envExportConditions = this._environment.exportConditions?.() ?? []; + this.esmConditions = Array.from( + new Set(['import', 'default', ...envExportConditions]) + ); + this.cjsConditions = Array.from( + new Set(['require', 'default', ...envExportConditions]) + ); + if (config.automock) { + config.setupFiles.forEach(filePath => { + if (filePath.includes(NODE_MODULES)) { + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + filePath, + undefined, + // shouldn't really matter, but in theory this will make sure the caching is correct + { + conditions: this.unstable_shouldLoadAsEsm(filePath) + ? this.esmConditions + : this.cjsConditions + } + ); + this._transitiveShouldMock.set(moduleID, false); + } + }); + } + this.resetModules(); + } + static shouldInstrument = _transform().shouldInstrument; + static async createContext(config, options) { + (0, _jestUtil().createDirectory)(config.cacheDirectory); + const instance = await Runtime.createHasteMap(config, { + console: options.console, + maxWorkers: options.maxWorkers, + resetCache: !config.cache, + watch: options.watch, + watchman: options.watchman + }); + const hasteMap = await instance.build(); + return { + config, + hasteFS: hasteMap.hasteFS, + moduleMap: hasteMap.moduleMap, + resolver: Runtime.createResolver(config, hasteMap.moduleMap) + }; + } + static createHasteMap(config, options) { + const ignorePatternParts = [ + ...config.modulePathIgnorePatterns, + ...(options && options.watch ? config.watchPathIgnorePatterns : []), + config.cacheDirectory.startsWith(config.rootDir + path().sep) && + config.cacheDirectory + ].filter(Boolean); + const ignorePattern = + ignorePatternParts.length > 0 + ? new RegExp(ignorePatternParts.join('|')) + : undefined; + return _jestHasteMap().default.create({ + cacheDirectory: config.cacheDirectory, + computeSha1: config.haste.computeSha1, + console: options?.console, + dependencyExtractor: config.dependencyExtractor, + enableSymlinks: config.haste.enableSymlinks, + extensions: [_jestSnapshot().EXTENSION].concat( + config.moduleFileExtensions + ), + forceNodeFilesystemAPI: config.haste.forceNodeFilesystemAPI, + hasteImplModulePath: config.haste.hasteImplModulePath, + hasteMapModulePath: config.haste.hasteMapModulePath, + id: config.id, + ignorePattern, + maxWorkers: options?.maxWorkers || 1, + mocksPattern: (0, _jestRegexUtil().escapePathForRegex)( + `${path().sep}__mocks__${path().sep}` + ), + platforms: config.haste.platforms || ['ios', 'android'], + resetCache: options?.resetCache, + retainAllFiles: config.haste.retainAllFiles || false, + rootDir: config.rootDir, + roots: config.roots, + throwOnModuleCollision: config.haste.throwOnModuleCollision, + useWatchman: options?.watchman, + watch: options?.watch + }); + } + static createResolver(config, moduleMap) { + return new (_jestResolve().default)(moduleMap, { + defaultPlatform: config.haste.defaultPlatform, + extensions: config.moduleFileExtensions.map(extension => `.${extension}`), + hasCoreModules: true, + moduleDirectories: config.moduleDirectories, + moduleNameMapper: getModuleNameMapper(config), + modulePaths: config.modulePaths, + platforms: config.haste.platforms, + resolver: config.resolver, + rootDir: config.rootDir + }); + } + static async runCLI() { + throw new Error('The jest-runtime CLI has been moved into jest-repl'); + } + static getCLIOptions() { + throw new Error('The jest-runtime CLI has been moved into jest-repl'); + } + + // unstable as it should be replaced by https://github.com/nodejs/modules/issues/393, and we don't want people to use it + unstable_shouldLoadAsEsm(path) { + return _jestResolve().default.unstable_shouldLoadAsEsm( + path, + this._config.extensionsToTreatAsEsm + ); + } + + // not async _now_, but transform will be + async loadEsmModule(modulePath, query = '') { + const cacheKey = modulePath + query; + if (this._fileTransformsMutex.has(cacheKey)) { + await this._fileTransformsMutex.get(cacheKey); + } + if (!this._esmoduleRegistry.has(cacheKey)) { + invariant( + typeof this._environment.getVmContext === 'function', + 'ES Modules are only supported if your test environment has the `getVmContext` function' + ); + const context = this._environment.getVmContext(); + invariant(context, 'Test environment has been torn down'); + let transformResolve; + let transformReject; + this._fileTransformsMutex.set( + cacheKey, + new Promise((resolve, reject) => { + transformResolve = resolve; + transformReject = reject; + }) + ); + invariant( + transformResolve && transformReject, + 'Promise initialization should be sync - please report this bug to Jest!' + ); + if (this._resolver.isCoreModule(modulePath)) { + const core = this._importCoreModule(modulePath, context); + this._esmoduleRegistry.set(cacheKey, core); + transformResolve(); + return core; + } + const transformedCode = await this.transformFileAsync(modulePath, { + isInternalModule: false, + supportsDynamicImport: true, + supportsExportNamespaceFrom: true, + supportsStaticESM: true, + supportsTopLevelAwait: true + }); + try { + const module = new (_vm().SourceTextModule)(transformedCode, { + context, + identifier: modulePath, + importModuleDynamically: async (specifier, referencingModule) => { + invariant( + runtimeSupportsVmModules, + 'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules' + ); + const module = await this.resolveModule( + specifier, + referencingModule.identifier, + referencingModule.context + ); + return this.linkAndEvaluateModule(module); + }, + initializeImportMeta: meta => { + meta.url = (0, _url().pathToFileURL)(modulePath).href; + let jest = this.jestObjectCaches.get(modulePath); + if (!jest) { + jest = this._createJestObjectFor(modulePath); + this.jestObjectCaches.set(modulePath, jest); + } + meta.jest = jest; + } + }); + invariant( + !this._esmoduleRegistry.has(cacheKey), + `Module cache already has entry ${cacheKey}. This is a bug in Jest, please report it!` + ); + this._esmoduleRegistry.set(cacheKey, module); + transformResolve(); + } catch (error) { + transformReject(error); + throw error; + } + } + const module = this._esmoduleRegistry.get(cacheKey); + invariant( + module, + 'Module cache does not contain module. This is a bug in Jest, please open up an issue' + ); + return module; + } + async resolveModule(specifier, referencingIdentifier, context) { + if (this.isTornDown) { + this._logFormattedReferenceError( + 'You are trying to `import` a file after the Jest environment has been torn down.' + ); + process.exitCode = 1; + // @ts-expect-error - exiting + return; + } + if (specifier === '@jest/globals') { + const fromCache = this._esmoduleRegistry.get('@jest/globals'); + if (fromCache) { + return fromCache; + } + const globals = this.getGlobalsForEsm(referencingIdentifier, context); + this._esmoduleRegistry.set('@jest/globals', globals); + return globals; + } + if (specifier.startsWith('data:')) { + if ( + await this._shouldMockModule( + referencingIdentifier, + specifier, + this._explicitShouldMockModule + ) + ) { + return this.importMock(referencingIdentifier, specifier, context); + } + const fromCache = this._esmoduleRegistry.get(specifier); + if (fromCache) { + return fromCache; + } + const match = specifier.match(dataURIRegex); + if (!match || !match.groups) { + throw new Error('Invalid data URI'); + } + const mime = match.groups.mime; + if (mime === 'application/wasm') { + throw new Error('WASM is currently not supported'); + } + const encoding = match.groups.encoding; + let code = match.groups.code; + if (!encoding || encoding === 'charset=utf-8') { + code = decodeURIComponent(code); + } else if (encoding === 'base64') { + code = Buffer.from(code, 'base64').toString(); + } else { + throw new Error(`Invalid data URI encoding: ${encoding}`); + } + let module; + if (mime === 'application/json') { + module = new (_vm().SyntheticModule)( + ['default'], + function () { + const obj = JSON.parse(code); + // @ts-expect-error: TS doesn't know what `this` is + this.setExport('default', obj); + }, + { + context, + identifier: specifier + } + ); + } else { + module = new (_vm().SourceTextModule)(code, { + context, + identifier: specifier, + importModuleDynamically: async (specifier, referencingModule) => { + invariant( + runtimeSupportsVmModules, + 'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules' + ); + const module = await this.resolveModule( + specifier, + referencingModule.identifier, + referencingModule.context + ); + return this.linkAndEvaluateModule(module); + }, + initializeImportMeta(meta) { + // no `jest` here as it's not loaded in a file + meta.url = specifier; + } + }); + } + this._esmoduleRegistry.set(specifier, module); + return module; + } + if (specifier.startsWith('file://')) { + specifier = (0, _url().fileURLToPath)(specifier); + } + const [path, query] = specifier.split('?'); + if ( + await this._shouldMockModule( + referencingIdentifier, + path, + this._explicitShouldMockModule + ) + ) { + return this.importMock(referencingIdentifier, path, context); + } + const resolved = await this._resolveModule(referencingIdentifier, path); + if ( + this._resolver.isCoreModule(resolved) || + this.unstable_shouldLoadAsEsm(resolved) + ) { + return this.loadEsmModule(resolved, query); + } + return this.loadCjsAsEsm(referencingIdentifier, resolved, context); + } + async linkAndEvaluateModule(module) { + if (this.isTornDown) { + this._logFormattedReferenceError( + 'You are trying to `import` a file after the Jest environment has been torn down.' + ); + process.exitCode = 1; + return; + } + if (module.status === 'unlinked') { + // since we might attempt to link the same module in parallel, stick the promise in a weak map so every call to + // this method can await it + this._esmModuleLinkingMap.set( + module, + module.link((specifier, referencingModule) => + this.resolveModule( + specifier, + referencingModule.identifier, + referencingModule.context + ) + ) + ); + } + await this._esmModuleLinkingMap.get(module); + if (module.status === 'linked') { + await module.evaluate(); + } + return module; + } + async unstable_importModule(from, moduleName) { + invariant( + runtimeSupportsVmModules, + 'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules' + ); + const [path, query] = (moduleName ?? '').split('?'); + const modulePath = await this._resolveModule(from, path); + const module = await this.loadEsmModule(modulePath, query); + return this.linkAndEvaluateModule(module); + } + loadCjsAsEsm(from, modulePath, context) { + // CJS loaded via `import` should share cache with other CJS: https://github.com/nodejs/modules/issues/503 + const cjs = this.requireModuleOrMock(from, modulePath); + const parsedExports = this.getExportsOfCjs(modulePath); + const cjsExports = [...parsedExports].filter(exportName => { + // we don't wanna respect any exports _named_ default as a named export + if (exportName === 'default') { + return false; + } + return Object.hasOwnProperty.call(cjs, exportName); + }); + const module = new (_vm().SyntheticModule)( + [...cjsExports, 'default'], + function () { + cjsExports.forEach(exportName => { + // @ts-expect-error: TS doesn't know what `this` is + this.setExport(exportName, cjs[exportName]); + }); + // @ts-expect-error: TS doesn't know what `this` is + this.setExport('default', cjs); + }, + { + context, + identifier: modulePath + } + ); + return evaluateSyntheticModule(module); + } + async importMock(from, moduleName, context) { + const moduleID = await this._resolver.getModuleIDAsync( + this._virtualModuleMocks, + from, + moduleName, + { + conditions: this.esmConditions + } + ); + if (this._moduleMockRegistry.has(moduleID)) { + return this._moduleMockRegistry.get(moduleID); + } + if (this._moduleMockFactories.has(moduleID)) { + const invokedFactory = await this._moduleMockFactories.get( + moduleID + // has check above makes this ok + )(); + + const module = new (_vm().SyntheticModule)( + Object.keys(invokedFactory), + function () { + Object.entries(invokedFactory).forEach(([key, value]) => { + // @ts-expect-error: TS doesn't know what `this` is + this.setExport(key, value); + }); + }, + { + context, + identifier: moduleName + } + ); + this._moduleMockRegistry.set(moduleID, module); + return evaluateSyntheticModule(module); + } + throw new Error('Attempting to import a mock without a factory'); + } + getExportsOfCjs(modulePath) { + const cachedNamedExports = this._cjsNamedExports.get(modulePath); + if (cachedNamedExports) { + return cachedNamedExports; + } + const transformedCode = + this._fileTransforms.get(modulePath)?.code ?? this.readFile(modulePath); + const {exports, reexports} = (0, _cjsModuleLexer().parse)(transformedCode); + const namedExports = new Set(exports); + reexports.forEach(reexport => { + const resolved = this._resolveCjsModule(modulePath, reexport); + const exports = this.getExportsOfCjs(resolved); + exports.forEach(namedExports.add, namedExports); + }); + this._cjsNamedExports.set(modulePath, namedExports); + return namedExports; + } + requireModule(from, moduleName, options, isRequireActual = false) { + const isInternal = options?.isInternalModule ?? false; + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + let modulePath; + + // Some old tests rely on this mocking behavior. Ideally we'll change this + // to be more explicit. + const moduleResource = moduleName && this._resolver.getModule(moduleName); + const manualMock = + moduleName && this._resolver.getMockModule(from, moduleName); + if ( + !options?.isInternalModule && + !isRequireActual && + !moduleResource && + manualMock && + manualMock !== this._isCurrentlyExecutingManualMock && + this._explicitShouldMock.get(moduleID) !== false + ) { + modulePath = manualMock; + } + if (moduleName && this._resolver.isCoreModule(moduleName)) { + return this._requireCoreModule( + moduleName, + supportsNodeColonModulePrefixInRequire + ); + } + if (!modulePath) { + modulePath = this._resolveCjsModule(from, moduleName); + } + if (this.unstable_shouldLoadAsEsm(modulePath)) { + // Node includes more info in the message + const error = new Error( + `Must use import to load ES Module: ${modulePath}` + ); + error.code = 'ERR_REQUIRE_ESM'; + throw error; + } + let moduleRegistry; + if (isInternal) { + moduleRegistry = this._internalModuleRegistry; + } else if (this._isolatedModuleRegistry) { + moduleRegistry = this._isolatedModuleRegistry; + } else { + moduleRegistry = this._moduleRegistry; + } + const module = moduleRegistry.get(modulePath); + if (module) { + return module.exports; + } + + // We must register the pre-allocated module object first so that any + // circular dependencies that may arise while evaluating the module can + // be satisfied. + const localModule = { + children: [], + exports: {}, + filename: modulePath, + id: modulePath, + loaded: false, + path: path().dirname(modulePath) + }; + moduleRegistry.set(modulePath, localModule); + try { + this._loadModule( + localModule, + from, + moduleName, + modulePath, + options, + moduleRegistry + ); + } catch (error) { + moduleRegistry.delete(modulePath); + throw error; + } + return localModule.exports; + } + requireInternalModule(from, to) { + if (to) { + const require = ( + _module().default.createRequire ?? + _module().default.createRequireFromPath + )(from); + if (INTERNAL_MODULE_REQUIRE_OUTSIDE_OPTIMIZED_MODULES.has(to)) { + return require(to); + } + const outsideJestVmPath = (0, _helpers.decodePossibleOutsideJestVmPath)( + to + ); + if (outsideJestVmPath) { + return require(outsideJestVmPath); + } + } + return this.requireModule(from, to, { + isInternalModule: true, + supportsDynamicImport: esmIsAvailable, + supportsExportNamespaceFrom: false, + supportsStaticESM: false, + supportsTopLevelAwait: false + }); + } + requireActual(from, moduleName) { + return this.requireModule(from, moduleName, undefined, true); + } + requireMock(from, moduleName) { + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + if (this._isolatedMockRegistry?.has(moduleID)) { + return this._isolatedMockRegistry.get(moduleID); + } else if (this._mockRegistry.has(moduleID)) { + return this._mockRegistry.get(moduleID); + } + const mockRegistry = this._isolatedMockRegistry || this._mockRegistry; + if (this._mockFactories.has(moduleID)) { + // has check above makes this ok + const module = this._mockFactories.get(moduleID)(); + mockRegistry.set(moduleID, module); + return module; + } + const manualMockOrStub = this._resolver.getMockModule(from, moduleName); + let modulePath = + this._resolver.getMockModule(from, moduleName) || + this._resolveCjsModule(from, moduleName); + let isManualMock = + manualMockOrStub && + !this._resolver.resolveStubModuleName(from, moduleName); + if (!isManualMock) { + // If the actual module file has a __mocks__ dir sitting immediately next + // to it, look to see if there is a manual mock for this file. + // + // subDir1/my_module.js + // subDir1/__mocks__/my_module.js + // subDir2/my_module.js + // subDir2/__mocks__/my_module.js + // + // Where some other module does a relative require into each of the + // respective subDir{1,2} directories and expects a manual mock + // corresponding to that particular my_module.js file. + + const moduleDir = path().dirname(modulePath); + const moduleFileName = path().basename(modulePath); + const potentialManualMock = path().join( + moduleDir, + '__mocks__', + moduleFileName + ); + if (fs().existsSync(potentialManualMock)) { + isManualMock = true; + modulePath = potentialManualMock; + } + } + if (isManualMock) { + const localModule = { + children: [], + exports: {}, + filename: modulePath, + id: modulePath, + loaded: false, + path: path().dirname(modulePath) + }; + this._loadModule( + localModule, + from, + moduleName, + modulePath, + undefined, + mockRegistry + ); + mockRegistry.set(moduleID, localModule.exports); + } else { + // Look for a real module to generate an automock from + mockRegistry.set(moduleID, this._generateMock(from, moduleName)); + } + return mockRegistry.get(moduleID); + } + _loadModule( + localModule, + from, + moduleName, + modulePath, + options, + moduleRegistry + ) { + if (path().extname(modulePath) === '.json') { + const text = (0, _stripBom().default)(this.readFile(modulePath)); + const transformedFile = this._scriptTransformer.transformJson( + modulePath, + this._getFullTransformationOptions(options), + text + ); + localModule.exports = + this._environment.global.JSON.parse(transformedFile); + } else if (path().extname(modulePath) === '.node') { + localModule.exports = require(modulePath); + } else { + // Only include the fromPath if a moduleName is given. Else treat as root. + const fromPath = moduleName ? from : null; + this._execModule(localModule, options, moduleRegistry, fromPath); + } + localModule.loaded = true; + } + _getFullTransformationOptions(options = defaultTransformOptions) { + return { + ...options, + ...this._coverageOptions + }; + } + requireModuleOrMock(from, moduleName) { + // this module is unmockable + if (moduleName === '@jest/globals') { + // @ts-expect-error: we don't care that it's not assignable to T + return this.getGlobalsForCjs(from); + } + try { + if (this._shouldMockCjs(from, moduleName, this._explicitShouldMock)) { + return this.requireMock(from, moduleName); + } else { + return this.requireModule(from, moduleName); + } + } catch (e) { + const moduleNotFound = + _jestResolve().default.tryCastModuleNotFoundError(e); + if (moduleNotFound) { + if ( + moduleNotFound.siblingWithSimilarExtensionFound === null || + moduleNotFound.siblingWithSimilarExtensionFound === undefined + ) { + moduleNotFound.hint = (0, _helpers.findSiblingsWithFileExtension)( + this._config.moduleFileExtensions, + from, + moduleNotFound.moduleName || moduleName + ); + moduleNotFound.siblingWithSimilarExtensionFound = Boolean( + moduleNotFound.hint + ); + } + moduleNotFound.buildMessage(this._config.rootDir); + throw moduleNotFound; + } + throw e; + } + } + isolateModules(fn) { + if (this._isolatedModuleRegistry || this._isolatedMockRegistry) { + throw new Error( + 'isolateModules cannot be nested inside another isolateModules.' + ); + } + this._isolatedModuleRegistry = new Map(); + this._isolatedMockRegistry = new Map(); + try { + fn(); + } finally { + // might be cleared within the callback + this._isolatedModuleRegistry?.clear(); + this._isolatedMockRegistry?.clear(); + this._isolatedModuleRegistry = null; + this._isolatedMockRegistry = null; + } + } + resetModules() { + this._isolatedModuleRegistry?.clear(); + this._isolatedMockRegistry?.clear(); + this._isolatedModuleRegistry = null; + this._isolatedMockRegistry = null; + this._mockRegistry.clear(); + this._moduleRegistry.clear(); + this._esmoduleRegistry.clear(); + this._fileTransformsMutex.clear(); + this._cjsNamedExports.clear(); + this._moduleMockRegistry.clear(); + this._cacheFS.clear(); + if ( + this._coverageOptions.collectCoverage && + this._coverageOptions.coverageProvider === 'v8' && + this._v8CoverageSources + ) { + this._v8CoverageSources = new Map([ + ...this._v8CoverageSources, + ...this._fileTransforms + ]); + } + this._fileTransforms.clear(); + if (this._environment) { + if (this._environment.global) { + const envGlobal = this._environment.global; + Object.keys(envGlobal).forEach(key => { + const globalMock = envGlobal[key]; + if ( + ((typeof globalMock === 'object' && globalMock !== null) || + typeof globalMock === 'function') && + globalMock._isMockFunction === true + ) { + globalMock.mockClear(); + } + }); + } + if (this._environment.fakeTimers) { + this._environment.fakeTimers.clearAllTimers(); + } + } + } + async collectV8Coverage() { + this._v8CoverageInstrumenter = + new (_collectV8Coverage().CoverageInstrumenter)(); + this._v8CoverageSources = new Map(); + await this._v8CoverageInstrumenter.startInstrumenting(); + } + async stopCollectingV8Coverage() { + if (!this._v8CoverageInstrumenter || !this._v8CoverageSources) { + throw new Error('You need to call `collectV8Coverage` first.'); + } + this._v8CoverageResult = + await this._v8CoverageInstrumenter.stopInstrumenting(); + this._v8CoverageSources = new Map([ + ...this._v8CoverageSources, + ...this._fileTransforms + ]); + } + getAllCoverageInfoCopy() { + return (0, _jestUtil().deepCyclicCopy)( + this._environment.global.__coverage__ + ); + } + getAllV8CoverageInfoCopy() { + if (!this._v8CoverageResult || !this._v8CoverageSources) { + throw new Error('You need to call `stopCollectingV8Coverage` first.'); + } + return this._v8CoverageResult + .filter(res => res.url.startsWith('file://')) + .map(res => ({ + ...res, + url: (0, _url().fileURLToPath)(res.url) + })) + .filter( + res => + // TODO: will this work on windows? It might be better if `shouldInstrument` deals with it anyways + res.url.startsWith(this._config.rootDir) && + this._v8CoverageSources.has(res.url) && + (0, _transform().shouldInstrument)( + res.url, + this._coverageOptions, + this._config + ) + ) + .map(result => { + const transformedFile = this._v8CoverageSources.get(result.url); + return { + codeTransformResult: transformedFile, + result + }; + }); + } + getSourceMaps() { + return this._sourceMapRegistry; + } + setMock(from, moduleName, mockFactory, options) { + if (options?.virtual) { + const mockPath = this._resolver.getModulePath(from, moduleName); + this._virtualMocks.set(mockPath, true); + } + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + this._explicitShouldMock.set(moduleID, true); + this._mockFactories.set(moduleID, mockFactory); + } + setModuleMock(from, moduleName, mockFactory, options) { + if (options?.virtual) { + const mockPath = this._resolver.getModulePath(from, moduleName); + this._virtualModuleMocks.set(mockPath, true); + } + const moduleID = this._resolver.getModuleID( + this._virtualModuleMocks, + from, + moduleName, + { + conditions: this.esmConditions + } + ); + this._explicitShouldMockModule.set(moduleID, true); + this._moduleMockFactories.set(moduleID, mockFactory); + } + restoreAllMocks() { + this._moduleMocker.restoreAllMocks(); + } + resetAllMocks() { + this._moduleMocker.resetAllMocks(); + } + clearAllMocks() { + this._moduleMocker.clearAllMocks(); + } + teardown() { + this.restoreAllMocks(); + this.resetAllMocks(); + this.resetModules(); + this._internalModuleRegistry.clear(); + this._mainModule = null; + this._mockFactories.clear(); + this._moduleMockFactories.clear(); + this._mockMetaDataCache.clear(); + this._shouldMockModuleCache.clear(); + this._shouldUnmockTransitiveDependenciesCache.clear(); + this._explicitShouldMock.clear(); + this._explicitShouldMockModule.clear(); + this._transitiveShouldMock.clear(); + this._virtualMocks.clear(); + this._virtualModuleMocks.clear(); + this._cacheFS.clear(); + this._unmockList = undefined; + this._sourceMapRegistry.clear(); + this._fileTransforms.clear(); + this.jestObjectCaches.clear(); + this._v8CoverageSources?.clear(); + this._v8CoverageResult = []; + this._v8CoverageInstrumenter = undefined; + this._moduleImplementation = undefined; + this.isTornDown = true; + } + _resolveCjsModule(from, to) { + return to + ? this._resolver.resolveModule(from, to, { + conditions: this.cjsConditions + }) + : from; + } + _resolveModule(from, to) { + return to + ? this._resolver.resolveModuleAsync(from, to, { + conditions: this.esmConditions + }) + : from; + } + _requireResolve(from, moduleName, options = {}) { + if (moduleName == null) { + throw new Error( + 'The first argument to require.resolve must be a string. Received null or undefined.' + ); + } + if (path().isAbsolute(moduleName)) { + const module = this._resolver.resolveModuleFromDirIfExists( + moduleName, + moduleName, + { + conditions: this.cjsConditions, + paths: [] + } + ); + if (module) { + return module; + } + } else { + const {paths} = options; + if (paths) { + for (const p of paths) { + const absolutePath = path().resolve(from, '..', p); + const module = this._resolver.resolveModuleFromDirIfExists( + absolutePath, + moduleName, + // required to also resolve files without leading './' directly in the path + { + conditions: this.cjsConditions, + paths: [absolutePath] + } + ); + if (module) { + return module; + } + } + throw new (_jestResolve().default.ModuleNotFoundError)( + `Cannot resolve module '${moduleName}' from paths ['${paths.join( + "', '" + )}'] from ${from}` + ); + } + } + try { + return this._resolveCjsModule(from, moduleName); + } catch (err) { + const module = this._resolver.getMockModule(from, moduleName); + if (module) { + return module; + } else { + throw err; + } + } + } + _requireResolvePaths(from, moduleName) { + if (moduleName == null) { + throw new Error( + 'The first argument to require.resolve.paths must be a string. Received null or undefined.' + ); + } + if (!moduleName.length) { + throw new Error( + 'The first argument to require.resolve.paths must not be the empty string.' + ); + } + if (moduleName[0] === '.') { + return [path().resolve(from, '..')]; + } + if (this._resolver.isCoreModule(moduleName)) { + return null; + } + return this._resolver.getModulePaths(path().resolve(from, '..')); + } + _execModule(localModule, options, moduleRegistry, from) { + if (this.isTornDown) { + this._logFormattedReferenceError( + 'You are trying to `import` a file after the Jest environment has been torn down.' + ); + process.exitCode = 1; + return; + } + + // If the environment was disposed, prevent this module from being executed. + if (!this._environment.global) { + return; + } + const module = localModule; + const filename = module.filename; + const lastExecutingModulePath = this._currentlyExecutingModulePath; + this._currentlyExecutingModulePath = filename; + const origCurrExecutingManualMock = this._isCurrentlyExecutingManualMock; + this._isCurrentlyExecutingManualMock = filename; + module.children = []; + Object.defineProperty(module, 'parent', { + enumerable: true, + get() { + const key = from || ''; + return moduleRegistry.get(key) || null; + } + }); + module.paths = this._resolver.getModulePaths(module.path); + Object.defineProperty(module, 'require', { + value: this._createRequireImplementation(module, options) + }); + const transformedCode = this.transformFile(filename, options); + let compiledFunction = null; + const script = this.createScriptFromCode(transformedCode, filename); + let runScript = null; + const vmContext = this._environment.getVmContext(); + if (vmContext) { + runScript = script.runInContext(vmContext, { + filename + }); + } + if (runScript !== null) { + compiledFunction = runScript[EVAL_RESULT_VARIABLE]; + } + if (compiledFunction === null) { + this._logFormattedReferenceError( + 'You are trying to `import` a file after the Jest environment has been torn down.' + ); + process.exitCode = 1; + return; + } + const jestObject = this._createJestObjectFor(filename); + this.jestObjectCaches.set(filename, jestObject); + const lastArgs = [ + this._config.injectGlobals ? jestObject : undefined, + // jest object + ...this._config.sandboxInjectedGlobals.map(globalVariable => { + if (this._environment.global[globalVariable]) { + return this._environment.global[globalVariable]; + } + throw new Error( + `You have requested '${globalVariable}' as a global variable, but it was not present. Please check your config or your global environment.` + ); + }) + ]; + if (!this._mainModule && filename === this._testPath) { + this._mainModule = module; + } + Object.defineProperty(module, 'main', { + enumerable: true, + value: this._mainModule + }); + try { + compiledFunction.call( + module.exports, + module, + // module object + module.exports, + // module exports + module.require, + // require implementation + module.path, + // __dirname + module.filename, + // __filename + lastArgs[0], + ...lastArgs.slice(1).filter(notEmpty) + ); + } catch (error) { + this.handleExecutionError(error, module); + } + this._isCurrentlyExecutingManualMock = origCurrExecutingManualMock; + this._currentlyExecutingModulePath = lastExecutingModulePath; + } + transformFile(filename, options) { + const source = this.readFile(filename); + if (options?.isInternalModule) { + return source; + } + let transformedFile = this._fileTransforms.get(filename); + if (transformedFile) { + return transformedFile.code; + } + transformedFile = this._scriptTransformer.transform( + filename, + this._getFullTransformationOptions(options), + source + ); + this._fileTransforms.set(filename, { + ...transformedFile, + wrapperLength: this.constructModuleWrapperStart().length + }); + if (transformedFile.sourceMapPath) { + this._sourceMapRegistry.set(filename, transformedFile.sourceMapPath); + } + return transformedFile.code; + } + async transformFileAsync(filename, options) { + const source = this.readFile(filename); + if (options?.isInternalModule) { + return source; + } + let transformedFile = this._fileTransforms.get(filename); + if (transformedFile) { + return transformedFile.code; + } + transformedFile = await this._scriptTransformer.transformAsync( + filename, + this._getFullTransformationOptions(options), + source + ); + this._fileTransforms.set(filename, { + ...transformedFile, + wrapperLength: 0 + }); + if (transformedFile.sourceMapPath) { + this._sourceMapRegistry.set(filename, transformedFile.sourceMapPath); + } + return transformedFile.code; + } + createScriptFromCode(scriptSource, filename) { + try { + const scriptFilename = this._resolver.isCoreModule(filename) + ? `jest-nodejs-core-${filename}` + : filename; + return new (_vm().Script)(this.wrapCodeInModuleWrapper(scriptSource), { + displayErrors: true, + filename: scriptFilename, + // @ts-expect-error: Experimental ESM API + importModuleDynamically: async specifier => { + invariant( + runtimeSupportsVmModules, + 'You need to run with a version of node that supports ES Modules in the VM API. See https://jestjs.io/docs/ecmascript-modules' + ); + const context = this._environment.getVmContext?.(); + invariant(context, 'Test environment has been torn down'); + const module = await this.resolveModule( + specifier, + scriptFilename, + context + ); + return this.linkAndEvaluateModule(module); + } + }); + } catch (e) { + throw (0, _transform().handlePotentialSyntaxError)(e); + } + } + _requireCoreModule(moduleName, supportPrefix) { + const moduleWithoutNodePrefix = + supportPrefix && moduleName.startsWith('node:') + ? moduleName.slice('node:'.length) + : moduleName; + if (moduleWithoutNodePrefix === 'process') { + return this._environment.global.process; + } + if (moduleWithoutNodePrefix === 'module') { + return this._getMockedNativeModule(); + } + return require(moduleWithoutNodePrefix); + } + _importCoreModule(moduleName, context) { + const required = this._requireCoreModule(moduleName, true); + const module = new (_vm().SyntheticModule)( + ['default', ...Object.keys(required)], + function () { + // @ts-expect-error: TS doesn't know what `this` is + this.setExport('default', required); + Object.entries(required).forEach(([key, value]) => { + // @ts-expect-error: TS doesn't know what `this` is + this.setExport(key, value); + }); + }, + // should identifier be `node://${moduleName}`? + { + context, + identifier: moduleName + } + ); + return evaluateSyntheticModule(module); + } + _getMockedNativeModule() { + if (this._moduleImplementation) { + return this._moduleImplementation; + } + const createRequire = modulePath => { + const filename = + typeof modulePath === 'string' + ? modulePath.startsWith('file:///') + ? (0, _url().fileURLToPath)(new (_url().URL)(modulePath)) + : modulePath + : (0, _url().fileURLToPath)(modulePath); + if (!path().isAbsolute(filename)) { + const error = new TypeError( + `The argument 'filename' must be a file URL object, file URL string, or absolute path string. Received '${filename}'` + ); + error.code = 'ERR_INVALID_ARG_TYPE'; + throw error; + } + return this._createRequireImplementation({ + children: [], + exports: {}, + filename, + id: filename, + loaded: false, + path: path().dirname(filename) + }); + }; + + // should we implement the class ourselves? + class Module extends _module().default.Module {} + Object.entries(_module().default.Module).forEach(([key, value]) => { + // @ts-expect-error: no index signature + Module[key] = value; + }); + Module.Module = Module; + if ('createRequire' in _module().default) { + Module.createRequire = createRequire; + } + if ('createRequireFromPath' in _module().default) { + Module.createRequireFromPath = function createRequireFromPath(filename) { + if (typeof filename !== 'string') { + const error = new TypeError( + `The argument 'filename' must be string. Received '${filename}'.${ + filename instanceof _url().URL + ? ' Use createRequire for URL filename.' + : '' + }` + ); + error.code = 'ERR_INVALID_ARG_TYPE'; + throw error; + } + return createRequire(filename); + }; + } + if ('syncBuiltinESMExports' in _module().default) { + // cast since TS seems very confused about whether it exists or not + Module.syncBuiltinESMExports = + // eslint-disable-next-line @typescript-eslint/no-empty-function + function syncBuiltinESMExports() {}; + } + this._moduleImplementation = Module; + return Module; + } + _generateMock(from, moduleName) { + const modulePath = + this._resolver.resolveStubModuleName(from, moduleName) || + this._resolveCjsModule(from, moduleName); + if (!this._mockMetaDataCache.has(modulePath)) { + // This allows us to handle circular dependencies while generating an + // automock + + this._mockMetaDataCache.set( + modulePath, + this._moduleMocker.getMetadata({}) || {} + ); + + // In order to avoid it being possible for automocking to potentially + // cause side-effects within the module environment, we need to execute + // the module in isolation. This could cause issues if the module being + // mocked has calls into side-effectful APIs on another module. + const origMockRegistry = this._mockRegistry; + const origModuleRegistry = this._moduleRegistry; + this._mockRegistry = new Map(); + this._moduleRegistry = new Map(); + const moduleExports = this.requireModule(from, moduleName); + + // Restore the "real" module/mock registries + this._mockRegistry = origMockRegistry; + this._moduleRegistry = origModuleRegistry; + const mockMetadata = this._moduleMocker.getMetadata(moduleExports); + if (mockMetadata == null) { + throw new Error( + `Failed to get mock metadata: ${modulePath}\n\n` + + 'See: https://jestjs.io/docs/manual-mocks#content' + ); + } + this._mockMetaDataCache.set(modulePath, mockMetadata); + } + return this._moduleMocker.generateFromMetadata( + // added above if missing + this._mockMetaDataCache.get(modulePath) + ); + } + _shouldMockCjs(from, moduleName, explicitShouldMock) { + const options = { + conditions: this.cjsConditions + }; + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + options + ); + const key = from + path().delimiter + moduleID; + if (explicitShouldMock.has(moduleID)) { + // guaranteed by `has` above + return explicitShouldMock.get(moduleID); + } + if ( + !this._shouldAutoMock || + this._resolver.isCoreModule(moduleName) || + this._shouldUnmockTransitiveDependenciesCache.get(key) + ) { + return false; + } + if (this._shouldMockModuleCache.has(moduleID)) { + // guaranteed by `has` above + return this._shouldMockModuleCache.get(moduleID); + } + let modulePath; + try { + modulePath = this._resolveCjsModule(from, moduleName); + } catch (e) { + const manualMock = this._resolver.getMockModule(from, moduleName); + if (manualMock) { + this._shouldMockModuleCache.set(moduleID, true); + return true; + } + throw e; + } + if (this._unmockList && this._unmockList.test(modulePath)) { + this._shouldMockModuleCache.set(moduleID, false); + return false; + } + + // transitive unmocking for package managers that store flat packages (npm3) + const currentModuleID = this._resolver.getModuleID( + this._virtualMocks, + from, + undefined, + options + ); + if ( + this._transitiveShouldMock.get(currentModuleID) === false || + (from.includes(NODE_MODULES) && + modulePath.includes(NODE_MODULES) && + ((this._unmockList && this._unmockList.test(from)) || + explicitShouldMock.get(currentModuleID) === false)) + ) { + this._transitiveShouldMock.set(moduleID, false); + this._shouldUnmockTransitiveDependenciesCache.set(key, true); + return false; + } + this._shouldMockModuleCache.set(moduleID, true); + return true; + } + async _shouldMockModule(from, moduleName, explicitShouldMock) { + const options = { + conditions: this.esmConditions + }; + const moduleID = await this._resolver.getModuleIDAsync( + this._virtualMocks, + from, + moduleName, + options + ); + const key = from + path().delimiter + moduleID; + if (explicitShouldMock.has(moduleID)) { + // guaranteed by `has` above + return explicitShouldMock.get(moduleID); + } + if ( + !this._shouldAutoMock || + this._resolver.isCoreModule(moduleName) || + this._shouldUnmockTransitiveDependenciesCache.get(key) + ) { + return false; + } + if (this._shouldMockModuleCache.has(moduleID)) { + // guaranteed by `has` above + return this._shouldMockModuleCache.get(moduleID); + } + let modulePath; + try { + modulePath = await this._resolveModule(from, moduleName); + } catch (e) { + const manualMock = await this._resolver.getMockModuleAsync( + from, + moduleName + ); + if (manualMock) { + this._shouldMockModuleCache.set(moduleID, true); + return true; + } + throw e; + } + if (this._unmockList && this._unmockList.test(modulePath)) { + this._shouldMockModuleCache.set(moduleID, false); + return false; + } + + // transitive unmocking for package managers that store flat packages (npm3) + const currentModuleID = await this._resolver.getModuleIDAsync( + this._virtualMocks, + from, + undefined, + options + ); + if ( + this._transitiveShouldMock.get(currentModuleID) === false || + (from.includes(NODE_MODULES) && + modulePath.includes(NODE_MODULES) && + ((this._unmockList && this._unmockList.test(from)) || + explicitShouldMock.get(currentModuleID) === false)) + ) { + this._transitiveShouldMock.set(moduleID, false); + this._shouldUnmockTransitiveDependenciesCache.set(key, true); + return false; + } + this._shouldMockModuleCache.set(moduleID, true); + return true; + } + _createRequireImplementation(from, options) { + const resolve = (moduleName, resolveOptions) => { + const resolved = this._requireResolve( + from.filename, + moduleName, + resolveOptions + ); + if ( + resolveOptions?.[JEST_RESOLVE_OUTSIDE_VM_OPTION] && + options?.isInternalModule + ) { + return (0, _helpers.createOutsideJestVmPath)(resolved); + } + return resolved; + }; + resolve.paths = moduleName => + this._requireResolvePaths(from.filename, moduleName); + const moduleRequire = options?.isInternalModule + ? moduleName => this.requireInternalModule(from.filename, moduleName) + : this.requireModuleOrMock.bind(this, from.filename); + moduleRequire.extensions = Object.create(null); + moduleRequire.resolve = resolve; + moduleRequire.cache = (() => { + // TODO: consider warning somehow that this does nothing. We should support deletions, anyways + const notPermittedMethod = () => true; + return new Proxy(Object.create(null), { + defineProperty: notPermittedMethod, + deleteProperty: notPermittedMethod, + get: (_target, key) => + typeof key === 'string' ? this._moduleRegistry.get(key) : undefined, + getOwnPropertyDescriptor() { + return { + configurable: true, + enumerable: true + }; + }, + has: (_target, key) => + typeof key === 'string' && this._moduleRegistry.has(key), + ownKeys: () => Array.from(this._moduleRegistry.keys()), + set: notPermittedMethod + }); + })(); + Object.defineProperty(moduleRequire, 'main', { + enumerable: true, + value: this._mainModule + }); + return moduleRequire; + } + _createJestObjectFor(from) { + const disableAutomock = () => { + this._shouldAutoMock = false; + return jestObject; + }; + const enableAutomock = () => { + this._shouldAutoMock = true; + return jestObject; + }; + const unmock = moduleName => { + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + this._explicitShouldMock.set(moduleID, false); + return jestObject; + }; + const deepUnmock = moduleName => { + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + this._explicitShouldMock.set(moduleID, false); + this._transitiveShouldMock.set(moduleID, false); + return jestObject; + }; + const mock = (moduleName, mockFactory, options) => { + if (mockFactory !== undefined) { + return setMockFactory(moduleName, mockFactory, options); + } + const moduleID = this._resolver.getModuleID( + this._virtualMocks, + from, + moduleName, + { + conditions: this.cjsConditions + } + ); + this._explicitShouldMock.set(moduleID, true); + return jestObject; + }; + const setMockFactory = (moduleName, mockFactory, options) => { + this.setMock(from, moduleName, mockFactory, options); + return jestObject; + }; + const mockModule = (moduleName, mockFactory, options) => { + if (typeof mockFactory !== 'function') { + throw new Error('`unstable_mockModule` must be passed a mock factory'); + } + this.setModuleMock(from, moduleName, mockFactory, options); + return jestObject; + }; + const clearAllMocks = () => { + this.clearAllMocks(); + return jestObject; + }; + const resetAllMocks = () => { + this.resetAllMocks(); + return jestObject; + }; + const restoreAllMocks = () => { + this.restoreAllMocks(); + return jestObject; + }; + const _getFakeTimers = () => { + if ( + this.isTornDown || + !(this._environment.fakeTimers || this._environment.fakeTimersModern) + ) { + this._logFormattedReferenceError( + 'You are trying to access a property or method of the Jest environment after it has been torn down.' + ); + process.exitCode = 1; + } + return this._fakeTimersImplementation; + }; + const useFakeTimers = fakeTimersConfig => { + fakeTimersConfig = { + ...this._config.fakeTimers, + ...fakeTimersConfig + }; + if (fakeTimersConfig?.legacyFakeTimers) { + this._fakeTimersImplementation = this._environment.fakeTimers; + } else { + this._fakeTimersImplementation = this._environment.fakeTimersModern; + } + this._fakeTimersImplementation.useFakeTimers(fakeTimersConfig); + return jestObject; + }; + const useRealTimers = () => { + _getFakeTimers().useRealTimers(); + return jestObject; + }; + const resetModules = () => { + this.resetModules(); + return jestObject; + }; + const isolateModules = fn => { + this.isolateModules(fn); + return jestObject; + }; + const fn = this._moduleMocker.fn.bind(this._moduleMocker); + const spyOn = this._moduleMocker.spyOn.bind(this._moduleMocker); + const mocked = + this._moduleMocker.mocked?.bind(this._moduleMocker) ?? + (() => { + throw new Error( + 'Your test environment does not support `mocked`, please update it.' + ); + }); + const setTimeout = timeout => { + this._environment.global[testTimeoutSymbol] = timeout; + return jestObject; + }; + const retryTimes = (numTestRetries, options) => { + this._environment.global[retryTimesSymbol] = numTestRetries; + this._environment.global[logErrorsBeforeRetrySymbol] = + options?.logErrorsBeforeRetry; + return jestObject; + }; + const jestObject = { + advanceTimersByTime: msToRun => + _getFakeTimers().advanceTimersByTime(msToRun), + advanceTimersToNextTimer: steps => + _getFakeTimers().advanceTimersToNextTimer(steps), + autoMockOff: disableAutomock, + autoMockOn: enableAutomock, + clearAllMocks, + clearAllTimers: () => _getFakeTimers().clearAllTimers(), + createMockFromModule: moduleName => this._generateMock(from, moduleName), + deepUnmock, + disableAutomock, + doMock: mock, + dontMock: unmock, + enableAutomock, + fn, + genMockFromModule: moduleName => this._generateMock(from, moduleName), + getRealSystemTime: () => { + const fakeTimers = _getFakeTimers(); + if (fakeTimers === this._environment.fakeTimersModern) { + return fakeTimers.getRealSystemTime(); + } else { + throw new TypeError( + '`jest.getRealSystemTime()` is not available when using legacy fake timers.' + ); + } + }, + getSeed: () => { + // TODO: remove this check in Jest 30 + if (this._globalConfig?.seed === undefined) { + throw new Error( + 'The seed value is not available. Likely you are using older versions of the jest dependencies.' + ); + } + return this._globalConfig.seed; + }, + getTimerCount: () => _getFakeTimers().getTimerCount(), + isMockFunction: this._moduleMocker.isMockFunction, + isolateModules, + mock, + mocked, + now: () => _getFakeTimers().now(), + requireActual: moduleName => this.requireActual(from, moduleName), + requireMock: moduleName => this.requireMock(from, moduleName), + resetAllMocks, + resetModules, + restoreAllMocks, + retryTimes, + runAllImmediates: () => { + const fakeTimers = _getFakeTimers(); + if (fakeTimers === this._environment.fakeTimers) { + fakeTimers.runAllImmediates(); + } else { + throw new TypeError( + '`jest.runAllImmediates()` is only available when using legacy fake timers.' + ); + } + }, + runAllTicks: () => _getFakeTimers().runAllTicks(), + runAllTimers: () => _getFakeTimers().runAllTimers(), + runOnlyPendingTimers: () => _getFakeTimers().runOnlyPendingTimers(), + setMock: (moduleName, mock) => setMockFactory(moduleName, () => mock), + setSystemTime: now => { + const fakeTimers = _getFakeTimers(); + if (fakeTimers === this._environment.fakeTimersModern) { + fakeTimers.setSystemTime(now); + } else { + throw new TypeError( + '`jest.setSystemTime()` is not available when using legacy fake timers.' + ); + } + }, + setTimeout, + spyOn, + unmock, + unstable_mockModule: mockModule, + useFakeTimers, + useRealTimers + }; + return jestObject; + } + _logFormattedReferenceError(errorMessage) { + const testPath = this._testPath + ? ` From ${(0, _slash().default)( + path().relative(this._config.rootDir, this._testPath) + )}.` + : ''; + const originalStack = new ReferenceError(`${errorMessage}${testPath}`).stack + .split('\n') + // Remove this file from the stack (jest-message-utils will keep one line) + .filter(line => line.indexOf(__filename) === -1) + .join('\n'); + const {message, stack} = (0, _jestMessageUtil().separateMessageFromStack)( + originalStack + ); + console.error( + `\n${message}\n${(0, _jestMessageUtil().formatStackTrace)( + stack, + this._config, + { + noStackTrace: false + } + )}` + ); + } + wrapCodeInModuleWrapper(content) { + return `${this.constructModuleWrapperStart() + content}\n}});`; + } + constructModuleWrapperStart() { + const args = this.constructInjectedModuleParameters(); + return `({"${EVAL_RESULT_VARIABLE}":function(${args.join(',')}){`; + } + constructInjectedModuleParameters() { + return [ + 'module', + 'exports', + 'require', + '__dirname', + '__filename', + this._config.injectGlobals ? 'jest' : undefined, + ...this._config.sandboxInjectedGlobals + ].filter(notEmpty); + } + handleExecutionError(e, module) { + const moduleNotFoundError = + _jestResolve().default.tryCastModuleNotFoundError(e); + if (moduleNotFoundError) { + if (!moduleNotFoundError.requireStack) { + moduleNotFoundError.requireStack = [module.filename || module.id]; + for (let cursor = module.parent; cursor; cursor = cursor.parent) { + moduleNotFoundError.requireStack.push(cursor.filename || cursor.id); + } + moduleNotFoundError.buildMessage(this._config.rootDir); + } + throw moduleNotFoundError; + } + throw e; + } + getGlobalsForCjs(from) { + const jest = this.jestObjectCaches.get(from); + invariant(jest, 'There should always be a Jest object already'); + return { + ...this.getGlobalsFromEnvironment(), + jest + }; + } + getGlobalsForEsm(from, context) { + let jest = this.jestObjectCaches.get(from); + if (!jest) { + jest = this._createJestObjectFor(from); + this.jestObjectCaches.set(from, jest); + } + const globals = { + ...this.getGlobalsFromEnvironment(), + jest + }; + const module = new (_vm().SyntheticModule)( + Object.keys(globals), + function () { + Object.entries(globals).forEach(([key, value]) => { + // @ts-expect-error: TS doesn't know what `this` is + this.setExport(key, value); + }); + }, + { + context, + identifier: '@jest/globals' + } + ); + return evaluateSyntheticModule(module); + } + getGlobalsFromEnvironment() { + if (this.jestGlobals) { + return { + ...this.jestGlobals + }; + } + return { + afterAll: this._environment.global.afterAll, + afterEach: this._environment.global.afterEach, + beforeAll: this._environment.global.beforeAll, + beforeEach: this._environment.global.beforeEach, + describe: this._environment.global.describe, + expect: this._environment.global.expect, + fdescribe: this._environment.global.fdescribe, + fit: this._environment.global.fit, + it: this._environment.global.it, + test: this._environment.global.test, + xdescribe: this._environment.global.xdescribe, + xit: this._environment.global.xit, + xtest: this._environment.global.xtest + }; + } + readFile(filename) { + let source = this._cacheFS.get(filename); + if (!source) { + source = fs().readFileSync(filename, 'utf8'); + this._cacheFS.set(filename, source); + } + return source; + } + setGlobalsForRuntime(globals) { + this.jestGlobals = globals; + } +} +exports.default = Runtime; +function invariant(condition, message) { + if (!condition) { + throw new Error(message); + } +} +function notEmpty(value) { + return value !== null && value !== undefined; +} +async function evaluateSyntheticModule(module) { + await module.link(() => { + throw new Error('This should never happen'); + }); + await module.evaluate(); + return module; +} diff --git a/node_modules/jest-runtime/package.json b/node_modules/jest-runtime/package.json new file mode 100644 index 0000000..0258b7b --- /dev/null +++ b/node_modules/jest-runtime/package.json @@ -0,0 +1,56 @@ +{ + "name": "jest-runtime", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-runtime" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/environment": "^29.2.2", + "@jest/fake-timers": "^29.2.2", + "@jest/globals": "^29.2.2", + "@jest/source-map": "^29.2.0", + "@jest/test-result": "^29.2.1", + "@jest/transform": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/node": "*", + "chalk": "^4.0.0", + "cjs-module-lexer": "^1.0.0", + "collect-v8-coverage": "^1.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.2.9", + "jest-haste-map": "^29.2.1", + "jest-message-util": "^29.2.1", + "jest-mock": "^29.2.2", + "jest-regex-util": "^29.2.0", + "jest-resolve": "^29.2.2", + "jest-snapshot": "^29.2.2", + "jest-util": "^29.2.1", + "slash": "^3.0.0", + "strip-bom": "^4.0.0" + }, + "devDependencies": { + "@jest/test-utils": "^29.2.1", + "@types/glob": "^7.1.1", + "@types/graceful-fs": "^4.1.3", + "jest-environment-node": "^29.2.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-snapshot/LICENSE b/node_modules/jest-snapshot/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-snapshot/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-snapshot/build/InlineSnapshots.js b/node_modules/jest-snapshot/build/InlineSnapshots.js new file mode 100644 index 0000000..537f3c5 --- /dev/null +++ b/node_modules/jest-snapshot/build/InlineSnapshots.js @@ -0,0 +1,416 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.saveInlineSnapshots = saveInlineSnapshots; +var path = _interopRequireWildcard(require('path')); +var _types = require('@babel/types'); +var fs = _interopRequireWildcard(require('graceful-fs')); +var _semver = _interopRequireDefault(require('semver')); +var _utils = require('./utils'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestWriteFile = + globalThis[Symbol.for('jest-native-write-file')] || fs.writeFileSync; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestReadFile = + globalThis[Symbol.for('jest-native-read-file')] || fs.readFileSync; +// prettier-ignore +const babelTraverse = // @ts-expect-error requireOutside Babel transform +require(require.resolve('@babel/traverse', { + [(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for('jest-resolve-outside-vm-option')]: true +})).default; +// prettier-ignore +const generate = // @ts-expect-error requireOutside Babel transform +require(require.resolve('@babel/generator', { + [(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for('jest-resolve-outside-vm-option')]: true +})).default; +// @ts-expect-error requireOutside Babel transform +const {file, templateElement, templateLiteral} = require(require.resolve( + '@babel/types', + { + [(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for( + 'jest-resolve-outside-vm-option' + )]: true + } +)); +// @ts-expect-error requireOutside Babel transform +const {parseSync} = require(require.resolve('@babel/core', { + [(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for( + 'jest-resolve-outside-vm-option' + )]: true +})); +function saveInlineSnapshots(snapshots, rootDir, prettierPath) { + let prettier = null; + if (prettierPath) { + try { + // @ts-expect-error requireOutside Babel transform + prettier = require(require.resolve(prettierPath, { + [(globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol).for( + 'jest-resolve-outside-vm-option' + )]: true + })); + } catch { + // Continue even if prettier is not installed. + } + } + const snapshotsByFile = groupSnapshotsByFile(snapshots); + for (const sourceFilePath of Object.keys(snapshotsByFile)) { + saveSnapshotsForFile( + snapshotsByFile[sourceFilePath], + sourceFilePath, + rootDir, + prettier && _semver.default.gte(prettier.version, '1.5.0') + ? prettier + : undefined + ); + } +} +const saveSnapshotsForFile = (snapshots, sourceFilePath, rootDir, prettier) => { + const sourceFile = jestReadFile(sourceFilePath, 'utf8'); + + // TypeScript projects may not have a babel config; make sure they can be parsed anyway. + const presets = [require.resolve('babel-preset-current-node-syntax')]; + const plugins = []; + if (/\.tsx?$/.test(sourceFilePath)) { + plugins.push([ + require.resolve('@babel/plugin-syntax-typescript'), + { + isTSX: sourceFilePath.endsWith('x') + }, + // unique name to make sure Babel does not complain about a possible duplicate plugin. + 'TypeScript syntax plugin added by Jest snapshot' + ]); + } + + // Record the matcher names seen during traversal and pass them down one + // by one to formatting parser. + const snapshotMatcherNames = []; + let ast = null; + try { + ast = parseSync(sourceFile, { + filename: sourceFilePath, + plugins, + presets, + root: rootDir + }); + } catch (error) { + // attempt to recover from missing jsx plugin + if (error.message.includes('@babel/plugin-syntax-jsx')) { + try { + const jsxSyntaxPlugin = [ + require.resolve('@babel/plugin-syntax-jsx'), + {}, + // unique name to make sure Babel does not complain about a possible duplicate plugin. + 'JSX syntax plugin added by Jest snapshot' + ]; + ast = parseSync(sourceFile, { + filename: sourceFilePath, + plugins: [...plugins, jsxSyntaxPlugin], + presets, + root: rootDir + }); + } catch { + throw error; + } + } else { + throw error; + } + } + if (!ast) { + throw new Error(`jest-snapshot: Failed to parse ${sourceFilePath}`); + } + traverseAst(snapshots, ast, snapshotMatcherNames); + + // substitute in the snapshots in reverse order, so slice calculations aren't thrown off. + const sourceFileWithSnapshots = snapshots.reduceRight( + (sourceSoFar, nextSnapshot) => { + if ( + !nextSnapshot.node || + typeof nextSnapshot.node.start !== 'number' || + typeof nextSnapshot.node.end !== 'number' + ) { + throw new Error('Jest: no snapshot insert location found'); + } + return ( + sourceSoFar.slice(0, nextSnapshot.node.start) + + generate(nextSnapshot.node, { + retainLines: true + }).code.trim() + + sourceSoFar.slice(nextSnapshot.node.end) + ); + }, + sourceFile + ); + const newSourceFile = prettier + ? runPrettier( + prettier, + sourceFilePath, + sourceFileWithSnapshots, + snapshotMatcherNames + ) + : sourceFileWithSnapshots; + if (newSourceFile !== sourceFile) { + jestWriteFile(sourceFilePath, newSourceFile); + } +}; +const groupSnapshotsBy = createKey => snapshots => + snapshots.reduce((object, inlineSnapshot) => { + const key = createKey(inlineSnapshot); + return { + ...object, + [key]: (object[key] || []).concat(inlineSnapshot) + }; + }, {}); +const groupSnapshotsByFrame = groupSnapshotsBy(({frame: {line, column}}) => + typeof line === 'number' && typeof column === 'number' + ? `${line}:${column - 1}` + : '' +); +const groupSnapshotsByFile = groupSnapshotsBy(({frame: {file}}) => file); +const indent = (snapshot, numIndents, indentation) => { + const lines = snapshot.split('\n'); + // Prevent re-indentation of inline snapshots. + if ( + lines.length >= 2 && + lines[1].startsWith(indentation.repeat(numIndents + 1)) + ) { + return snapshot; + } + return lines + .map((line, index) => { + if (index === 0) { + // First line is either a 1-line snapshot or a blank line. + return line; + } else if (index !== lines.length - 1) { + // Do not indent empty lines. + if (line === '') { + return line; + } + + // Not last line, indent one level deeper than expect call. + return indentation.repeat(numIndents + 1) + line; + } else { + // The last line should be placed on the same level as the expect call. + return indentation.repeat(numIndents) + line; + } + }) + .join('\n'); +}; +const resolveAst = fileOrProgram => { + // Flow uses a 'Program' parent node, babel expects a 'File'. + let ast = fileOrProgram; + if (ast.type !== 'File') { + ast = file(ast, ast.comments, ast.tokens); + delete ast.program.comments; + } + return ast; +}; +const traverseAst = (snapshots, fileOrProgram, snapshotMatcherNames) => { + const ast = resolveAst(fileOrProgram); + const groupedSnapshots = groupSnapshotsByFrame(snapshots); + const remainingSnapshots = new Set(snapshots.map(({snapshot}) => snapshot)); + babelTraverse(ast, { + CallExpression({node}) { + const {arguments: args, callee} = node; + if ( + callee.type !== 'MemberExpression' || + callee.property.type !== 'Identifier' || + callee.property.loc == null + ) { + return; + } + const {line, column} = callee.property.loc.start; + const snapshotsForFrame = groupedSnapshots[`${line}:${column}`]; + if (!snapshotsForFrame) { + return; + } + if (snapshotsForFrame.length > 1) { + throw new Error( + 'Jest: Multiple inline snapshots for the same call are not supported.' + ); + } + snapshotMatcherNames.push(callee.property.name); + const snapshotIndex = args.findIndex( + ({type}) => type === 'TemplateLiteral' + ); + const values = snapshotsForFrame.map(inlineSnapshot => { + inlineSnapshot.node = node; + const {snapshot} = inlineSnapshot; + remainingSnapshots.delete(snapshot); + return templateLiteral( + [ + templateElement({ + raw: (0, _utils.escapeBacktickString)(snapshot) + }) + ], + [] + ); + }); + const replacementNode = values[0]; + if (snapshotIndex > -1) { + args[snapshotIndex] = replacementNode; + } else { + args.push(replacementNode); + } + } + }); + if (remainingSnapshots.size) { + throw new Error("Jest: Couldn't locate all inline snapshots."); + } +}; +const runPrettier = ( + prettier, + sourceFilePath, + sourceFileWithSnapshots, + snapshotMatcherNames +) => { + // Resolve project configuration. + // For older versions of Prettier, do not load configuration. + const config = prettier.resolveConfig + ? prettier.resolveConfig.sync(sourceFilePath, { + editorconfig: true + }) + : null; + + // Prioritize parser found in the project config. + // If not found detect the parser for the test file. + // For older versions of Prettier, fallback to a simple parser detection. + // @ts-expect-error - `inferredParser` is `string` + const inferredParser = + (config && typeof config.parser === 'string' && config.parser) || + (prettier.getFileInfo + ? prettier.getFileInfo.sync(sourceFilePath).inferredParser + : simpleDetectParser(sourceFilePath)); + if (!inferredParser) { + throw new Error( + `Could not infer Prettier parser for file ${sourceFilePath}` + ); + } + + // Snapshots have now been inserted. Run prettier to make sure that the code is + // formatted, except snapshot indentation. Snapshots cannot be formatted until + // after the initial format because we don't know where the call expression + // will be placed (specifically its indentation), so we have to do two + // prettier.format calls back-to-back. + return prettier.format( + prettier.format(sourceFileWithSnapshots, { + ...config, + filepath: sourceFilePath + }), + { + ...config, + filepath: sourceFilePath, + parser: createFormattingParser(snapshotMatcherNames, inferredParser) + } + ); +}; + +// This parser formats snapshots to the correct indentation. +const createFormattingParser = + (snapshotMatcherNames, inferredParser) => (text, parsers, options) => { + // Workaround for https://github.com/prettier/prettier/issues/3150 + options.parser = inferredParser; + const ast = resolveAst(parsers[inferredParser](text, options)); + babelTraverse(ast, { + CallExpression({node: {arguments: args, callee}, parent}) { + if ( + callee.type !== 'MemberExpression' || + callee.property.type !== 'Identifier' || + !snapshotMatcherNames.includes(callee.property.name) || + !callee.loc || + callee.computed + ) { + return; + } + let snapshotIndex; + let snapshot; + for (let i = 0; i < args.length; i++) { + const node = args[i]; + if (node.type === 'TemplateLiteral') { + snapshotIndex = i; + snapshot = node.quasis[0].value.raw; + } + } + if (snapshot === undefined || snapshotIndex === undefined) { + return; + } + const startColumn = + (0, _types.isAwaitExpression)(parent) && parent.loc + ? parent.loc.start.column + : callee.loc.start.column; + const useSpaces = !options.useTabs; + snapshot = indent( + snapshot, + Math.ceil( + useSpaces + ? startColumn / (options.tabWidth ?? 1) + : // Each tab is 2 characters. + startColumn / 2 + ), + useSpaces ? ' '.repeat(options.tabWidth ?? 1) : '\t' + ); + const replacementNode = templateLiteral( + [ + templateElement({ + raw: snapshot + }) + ], + [] + ); + args[snapshotIndex] = replacementNode; + } + }); + return ast; + }; +const simpleDetectParser = filePath => { + const extname = path.extname(filePath); + if (/\.tsx?$/.test(extname)) { + return 'typescript'; + } + return 'babel'; +}; diff --git a/node_modules/jest-snapshot/build/SnapshotResolver.js b/node_modules/jest-snapshot/build/SnapshotResolver.js new file mode 100644 index 0000000..88b3676 --- /dev/null +++ b/node_modules/jest-snapshot/build/SnapshotResolver.js @@ -0,0 +1,153 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.isSnapshotPath = + exports.buildSnapshotResolver = + exports.EXTENSION = + exports.DOT_EXTENSION = + void 0; +var path = _interopRequireWildcard(require('path')); +var _chalk = _interopRequireDefault(require('chalk')); +var _transform = require('@jest/transform'); +var _jestUtil = require('jest-util'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const EXTENSION = 'snap'; +exports.EXTENSION = EXTENSION; +const DOT_EXTENSION = `.${EXTENSION}`; +exports.DOT_EXTENSION = DOT_EXTENSION; +const isSnapshotPath = path => path.endsWith(DOT_EXTENSION); +exports.isSnapshotPath = isSnapshotPath; +const cache = new Map(); +const buildSnapshotResolver = async ( + config, + localRequire = (0, _transform.createTranspilingRequire)(config) +) => { + const key = config.rootDir; + const resolver = + cache.get(key) ?? + (await createSnapshotResolver(await localRequire, config.snapshotResolver)); + cache.set(key, resolver); + return resolver; +}; +exports.buildSnapshotResolver = buildSnapshotResolver; +async function createSnapshotResolver(localRequire, snapshotResolverPath) { + return typeof snapshotResolverPath === 'string' + ? createCustomSnapshotResolver(snapshotResolverPath, localRequire) + : createDefaultSnapshotResolver(); +} +function createDefaultSnapshotResolver() { + return { + resolveSnapshotPath: testPath => + path.join( + path.join(path.dirname(testPath), '__snapshots__'), + path.basename(testPath) + DOT_EXTENSION + ), + resolveTestPath: snapshotPath => + path.resolve( + path.dirname(snapshotPath), + '..', + path.basename(snapshotPath, DOT_EXTENSION) + ), + testPathForConsistencyCheck: path.posix.join( + 'consistency_check', + '__tests__', + 'example.test.js' + ) + }; +} +async function createCustomSnapshotResolver( + snapshotResolverPath, + localRequire +) { + const custom = (0, _jestUtil.interopRequireDefault)( + await localRequire(snapshotResolverPath) + ).default; + const keys = [ + ['resolveSnapshotPath', 'function'], + ['resolveTestPath', 'function'], + ['testPathForConsistencyCheck', 'string'] + ]; + keys.forEach(([propName, requiredType]) => { + if (typeof custom[propName] !== requiredType) { + throw new TypeError(mustImplement(propName, requiredType)); + } + }); + const customResolver = { + resolveSnapshotPath: testPath => + custom.resolveSnapshotPath(testPath, DOT_EXTENSION), + resolveTestPath: snapshotPath => + custom.resolveTestPath(snapshotPath, DOT_EXTENSION), + testPathForConsistencyCheck: custom.testPathForConsistencyCheck + }; + verifyConsistentTransformations(customResolver); + return customResolver; +} +function mustImplement(propName, requiredType) { + return `${_chalk.default.bold( + `Custom snapshot resolver must implement a \`${propName}\` as a ${requiredType}.` + )}\nDocumentation: https://jestjs.io/docs/configuration#snapshotresolver-string`; +} +function verifyConsistentTransformations(custom) { + const resolvedSnapshotPath = custom.resolveSnapshotPath( + custom.testPathForConsistencyCheck + ); + const resolvedTestPath = custom.resolveTestPath(resolvedSnapshotPath); + if (resolvedTestPath !== custom.testPathForConsistencyCheck) { + throw new Error( + _chalk.default.bold( + `Custom snapshot resolver functions must transform paths consistently, i.e. expects resolveTestPath(resolveSnapshotPath('${custom.testPathForConsistencyCheck}')) === ${resolvedTestPath}` + ) + ); + } +} diff --git a/node_modules/jest-snapshot/build/State.js b/node_modules/jest-snapshot/build/State.js new file mode 100644 index 0000000..f2ba4dd --- /dev/null +++ b/node_modules/jest-snapshot/build/State.js @@ -0,0 +1,282 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var fs = _interopRequireWildcard(require('graceful-fs')); +var _jestMessageUtil = require('jest-message-util'); +var _InlineSnapshots = require('./InlineSnapshots'); +var _utils = require('./utils'); +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestExistsFile = + globalThis[Symbol.for('jest-native-exists-file')] || fs.existsSync; +class SnapshotState { + _counters; + _dirty; + // @ts-expect-error - seemingly unused? + _index; + _updateSnapshot; + _snapshotData; + _initialData; + _snapshotPath; + _inlineSnapshots; + _uncheckedKeys; + _prettierPath; + _rootDir; + snapshotFormat; + added; + expand; + matched; + unmatched; + updated; + constructor(snapshotPath, options) { + this._snapshotPath = snapshotPath; + const {data, dirty} = (0, _utils.getSnapshotData)( + this._snapshotPath, + options.updateSnapshot + ); + this._initialData = data; + this._snapshotData = data; + this._dirty = dirty; + this._prettierPath = options.prettierPath ?? null; + this._inlineSnapshots = []; + this._uncheckedKeys = new Set(Object.keys(this._snapshotData)); + this._counters = new Map(); + this._index = 0; + this.expand = options.expand || false; + this.added = 0; + this.matched = 0; + this.unmatched = 0; + this._updateSnapshot = options.updateSnapshot; + this.updated = 0; + this.snapshotFormat = options.snapshotFormat; + this._rootDir = options.rootDir; + } + markSnapshotsAsCheckedForTest(testName) { + this._uncheckedKeys.forEach(uncheckedKey => { + if ((0, _utils.keyToTestName)(uncheckedKey) === testName) { + this._uncheckedKeys.delete(uncheckedKey); + } + }); + } + _addSnapshot(key, receivedSerialized, options) { + this._dirty = true; + if (options.isInline) { + const error = options.error || new Error(); + const lines = (0, _jestMessageUtil.getStackTraceLines)( + (0, _utils.removeLinesBeforeExternalMatcherTrap)(error.stack || '') + ); + const frame = (0, _jestMessageUtil.getTopFrame)(lines); + if (!frame) { + throw new Error( + "Jest: Couldn't infer stack frame for inline snapshot." + ); + } + this._inlineSnapshots.push({ + frame, + snapshot: receivedSerialized + }); + } else { + this._snapshotData[key] = receivedSerialized; + } + } + clear() { + this._snapshotData = this._initialData; + this._inlineSnapshots = []; + this._counters = new Map(); + this._index = 0; + this.added = 0; + this.matched = 0; + this.unmatched = 0; + this.updated = 0; + } + save() { + const hasExternalSnapshots = Object.keys(this._snapshotData).length; + const hasInlineSnapshots = this._inlineSnapshots.length; + const isEmpty = !hasExternalSnapshots && !hasInlineSnapshots; + const status = { + deleted: false, + saved: false + }; + if ((this._dirty || this._uncheckedKeys.size) && !isEmpty) { + if (hasExternalSnapshots) { + (0, _utils.saveSnapshotFile)(this._snapshotData, this._snapshotPath); + } + if (hasInlineSnapshots) { + (0, _InlineSnapshots.saveInlineSnapshots)( + this._inlineSnapshots, + this._rootDir, + this._prettierPath + ); + } + status.saved = true; + } else if (!hasExternalSnapshots && jestExistsFile(this._snapshotPath)) { + if (this._updateSnapshot === 'all') { + fs.unlinkSync(this._snapshotPath); + } + status.deleted = true; + } + return status; + } + getUncheckedCount() { + return this._uncheckedKeys.size || 0; + } + getUncheckedKeys() { + return Array.from(this._uncheckedKeys); + } + removeUncheckedKeys() { + if (this._updateSnapshot === 'all' && this._uncheckedKeys.size) { + this._dirty = true; + this._uncheckedKeys.forEach(key => delete this._snapshotData[key]); + this._uncheckedKeys.clear(); + } + } + match({testName, received, key, inlineSnapshot, isInline, error}) { + this._counters.set(testName, (this._counters.get(testName) || 0) + 1); + const count = Number(this._counters.get(testName)); + if (!key) { + key = (0, _utils.testNameToKey)(testName, count); + } + + // Do not mark the snapshot as "checked" if the snapshot is inline and + // there's an external snapshot. This way the external snapshot can be + // removed with `--updateSnapshot`. + if (!(isInline && this._snapshotData[key] !== undefined)) { + this._uncheckedKeys.delete(key); + } + const receivedSerialized = (0, _utils.addExtraLineBreaks)( + (0, _utils.serialize)(received, undefined, this.snapshotFormat) + ); + const expected = isInline ? inlineSnapshot : this._snapshotData[key]; + const pass = expected === receivedSerialized; + const hasSnapshot = expected !== undefined; + const snapshotIsPersisted = isInline || fs.existsSync(this._snapshotPath); + if (pass && !isInline) { + // Executing a snapshot file as JavaScript and writing the strings back + // when other snapshots have changed loses the proper escaping for some + // characters. Since we check every snapshot in every test, use the newly + // generated formatted string. + // Note that this is only relevant when a snapshot is added and the dirty + // flag is set. + this._snapshotData[key] = receivedSerialized; + } + + // These are the conditions on when to write snapshots: + // * There's no snapshot file in a non-CI environment. + // * There is a snapshot file and we decided to update the snapshot. + // * There is a snapshot file, but it doesn't have this snaphsot. + // These are the conditions on when not to write snapshots: + // * The update flag is set to 'none'. + // * There's no snapshot file or a file without this snapshot on a CI environment. + if ( + (hasSnapshot && this._updateSnapshot === 'all') || + ((!hasSnapshot || !snapshotIsPersisted) && + (this._updateSnapshot === 'new' || this._updateSnapshot === 'all')) + ) { + if (this._updateSnapshot === 'all') { + if (!pass) { + if (hasSnapshot) { + this.updated++; + } else { + this.added++; + } + this._addSnapshot(key, receivedSerialized, { + error, + isInline + }); + } else { + this.matched++; + } + } else { + this._addSnapshot(key, receivedSerialized, { + error, + isInline + }); + this.added++; + } + return { + actual: '', + count, + expected: '', + key, + pass: true + }; + } else { + if (!pass) { + this.unmatched++; + return { + actual: (0, _utils.removeExtraLineBreaks)(receivedSerialized), + count, + expected: + expected !== undefined + ? (0, _utils.removeExtraLineBreaks)(expected) + : undefined, + key, + pass: false + }; + } else { + this.matched++; + return { + actual: '', + count, + expected: '', + key, + pass: true + }; + } + } + } + fail(testName, _received, key) { + this._counters.set(testName, (this._counters.get(testName) || 0) + 1); + const count = Number(this._counters.get(testName)); + if (!key) { + key = (0, _utils.testNameToKey)(testName, count); + } + this._uncheckedKeys.delete(key); + this.unmatched++; + return key; + } +} +exports.default = SnapshotState; diff --git a/node_modules/jest-snapshot/build/colors.js b/node_modules/jest-snapshot/build/colors.js new file mode 100644 index 0000000..b2e5732 --- /dev/null +++ b/node_modules/jest-snapshot/build/colors.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.bForeground3 = + exports.bForeground2 = + exports.bBackground3 = + exports.bBackground2 = + exports.aForeground3 = + exports.aForeground2 = + exports.aBackground3 = + exports.aBackground2 = + void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// https://jonasjacek.github.io/colors/ + +const aForeground2 = 90; +exports.aForeground2 = aForeground2; +const aBackground2 = 225; +exports.aBackground2 = aBackground2; +const bForeground2 = 23; +exports.bForeground2 = bForeground2; +const bBackground2 = 195; +exports.bBackground2 = bBackground2; +const aForeground3 = [0x80, 0, 0x80]; +exports.aForeground3 = aForeground3; +const aBackground3 = [0xff, 0xd7, 0xff]; +exports.aBackground3 = aBackground3; +const bForeground3 = [0, 0x5f, 0x5f]; +exports.bForeground3 = bForeground3; +const bBackground3 = [0xd7, 0xff, 0xff]; +exports.bBackground3 = bBackground3; diff --git a/node_modules/jest-snapshot/build/dedentLines.js b/node_modules/jest-snapshot/build/dedentLines.js new file mode 100644 index 0000000..6e13815 --- /dev/null +++ b/node_modules/jest-snapshot/build/dedentLines.js @@ -0,0 +1,132 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.dedentLines = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const getIndentationLength = line => { + const result = /^( {2})+/.exec(line); + return result === null ? 0 : result[0].length; +}; +const dedentLine = line => line.slice(getIndentationLength(line)); + +// Return true if: +// "key": "value has multiple lines\n… +// "key has multiple lines\n… +const hasUnmatchedDoubleQuoteMarks = string => { + let n = 0; + let i = string.indexOf('"', 0); + while (i !== -1) { + if (i === 0 || string[i - 1] !== '\\') { + n += 1; + } + i = string.indexOf('"', i + 1); + } + return n % 2 !== 0; +}; +const isFirstLineOfTag = line => /^( {2})* { + let line = input[output.length]; + output.push(dedentLine(line)); + if (line.includes('>')) { + return true; + } + while (output.length < input.length) { + line = input[output.length]; + if (hasUnmatchedDoubleQuoteMarks(line)) { + return false; // because props include a multiline string + } else if (isFirstLineOfTag(line)) { + // Recursion only if props have markup. + if (!dedentMarkup(input, output)) { + return false; + } + } else { + output.push(dedentLine(line)); + if (line.includes('>')) { + return true; + } + } + } + return false; +}; + +// Push dedented lines of markup onto output and return true; +// otherwise return false because: +// * props include a multiline string +// * text has more than one adjacent line +// * markup does not close +const dedentMarkup = (input, output) => { + let line = input[output.length]; + if (!dedentStartTag(input, output)) { + return false; + } + if (input[output.length - 1].includes('/>')) { + return true; + } + let isText = false; + const stack = []; + stack.push(getIndentationLength(line)); + while (stack.length > 0 && output.length < input.length) { + line = input[output.length]; + if (isFirstLineOfTag(line)) { + if (line.includes('')) { + stack.push(getIndentationLength(line)); + } + } + isText = false; + } else { + if (isText) { + return false; // because text has more than one adjacent line + } + + const indentationLengthOfTag = stack[stack.length - 1]; + output.push(line.slice(indentationLengthOfTag + 2)); + isText = true; + } + } + return stack.length === 0; +}; + +// Return lines unindented by heuristic; +// otherwise return null because: +// * props include a multiline string +// * text has more than one adjacent line +// * markup does not close +const dedentLines = input => { + const output = []; + while (output.length < input.length) { + const line = input[output.length]; + if (hasUnmatchedDoubleQuoteMarks(line)) { + return null; + } else if (isFirstLineOfTag(line)) { + if (!dedentMarkup(input, output)) { + return null; + } + } else { + output.push(dedentLine(line)); + } + } + return output; +}; +exports.dedentLines = dedentLines; diff --git a/node_modules/jest-snapshot/build/index.d.ts b/node_modules/jest-snapshot/build/index.d.ts new file mode 100644 index 0000000..8a21545 --- /dev/null +++ b/node_modules/jest-snapshot/build/index.d.ts @@ -0,0 +1,182 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config} from '@jest/types'; +import type {IHasteFS} from 'jest-haste-map'; +import type {MatcherContext} from 'expect'; +import type {MatcherFunctionWithContext} from 'expect'; +import {Plugin as Plugin_2} from 'pretty-format'; +import {Plugins} from 'pretty-format'; +import type {PrettyFormatOptions} from 'pretty-format'; + +export declare const addSerializer: (plugin: Plugin_2) => void; + +export declare const buildSnapshotResolver: ( + config: Config.ProjectConfig, + localRequire?: Promise | LocalRequire, +) => Promise; + +export declare const cleanup: ( + hasteFS: IHasteFS, + update: Config.SnapshotUpdateState, + snapshotResolver: SnapshotResolver, + testPathIgnorePatterns?: Config.ProjectConfig['testPathIgnorePatterns'], +) => { + filesRemoved: number; + filesRemovedList: Array; +}; + +export declare interface Context extends MatcherContext { + snapshotState: SnapshotState; +} + +export declare const EXTENSION = 'snap'; + +export declare const getSerializers: () => Plugins; + +export declare const isSnapshotPath: (path: string) => boolean; + +declare type LocalRequire = (module: string) => unknown; + +declare type SaveStatus = { + deleted: boolean; + saved: boolean; +}; + +declare type SnapshotFormat = Omit; + +export declare interface SnapshotMatchers, T> { + /** + * This ensures that a value matches the most recent snapshot with property matchers. + * Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information. + */ + toMatchSnapshot(hint?: string): R; + /** + * This ensures that a value matches the most recent snapshot. + * Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information. + */ + toMatchSnapshot>( + propertyMatchers: Partial, + hint?: string, + ): R; + /** + * This ensures that a value matches the most recent snapshot with property matchers. + * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. + * Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information. + */ + toMatchInlineSnapshot(snapshot?: string): R; + /** + * This ensures that a value matches the most recent snapshot with property matchers. + * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. + * Check out [the Snapshot Testing guide](https://jestjs.io/docs/snapshot-testing) for more information. + */ + toMatchInlineSnapshot>( + propertyMatchers: Partial, + snapshot?: string, + ): R; + /** + * Used to test that a function throws a error matching the most recent snapshot when it is called. + */ + toThrowErrorMatchingSnapshot(hint?: string): R; + /** + * Used to test that a function throws a error matching the most recent snapshot when it is called. + * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. + */ + toThrowErrorMatchingInlineSnapshot(snapshot?: string): R; +} + +declare type SnapshotMatchOptions = { + readonly testName: string; + readonly received: unknown; + readonly key?: string; + readonly inlineSnapshot?: string; + readonly isInline: boolean; + readonly error?: Error; +}; + +export declare type SnapshotResolver = { + /** Resolves from `testPath` to snapshot path. */ + resolveSnapshotPath(testPath: string, snapshotExtension?: string): string; + /** Resolves from `snapshotPath` to test path. */ + resolveTestPath(snapshotPath: string, snapshotExtension?: string): string; + /** Example test path, used for preflight consistency check of the implementation above. */ + testPathForConsistencyCheck: string; +}; + +declare type SnapshotReturnOptions = { + readonly actual: string; + readonly count: number; + readonly expected?: string; + readonly key: string; + readonly pass: boolean; +}; + +export declare class SnapshotState { + private _counters; + private _dirty; + private _index; + private readonly _updateSnapshot; + private _snapshotData; + private readonly _initialData; + private readonly _snapshotPath; + private _inlineSnapshots; + private readonly _uncheckedKeys; + private readonly _prettierPath; + private readonly _rootDir; + readonly snapshotFormat: SnapshotFormat; + added: number; + expand: boolean; + matched: number; + unmatched: number; + updated: number; + constructor(snapshotPath: string, options: SnapshotStateOptions); + markSnapshotsAsCheckedForTest(testName: string): void; + private _addSnapshot; + clear(): void; + save(): SaveStatus; + getUncheckedCount(): number; + getUncheckedKeys(): Array; + removeUncheckedKeys(): void; + match({ + testName, + received, + key, + inlineSnapshot, + isInline, + error, + }: SnapshotMatchOptions): SnapshotReturnOptions; + fail(testName: string, _received: unknown, key?: string): string; +} + +declare type SnapshotStateOptions = { + readonly updateSnapshot: Config.SnapshotUpdateState; + readonly prettierPath?: string | null; + readonly expand?: boolean; + readonly snapshotFormat: SnapshotFormat; + readonly rootDir: string; +}; + +export declare const toMatchInlineSnapshot: MatcherFunctionWithContext< + Context, + [propertiesOrSnapshot?: object | string, inlineSnapshot?: string] +>; + +export declare const toMatchSnapshot: MatcherFunctionWithContext< + Context, + [propertiesOrHint?: object | string, hint?: string] +>; + +export declare const toThrowErrorMatchingInlineSnapshot: MatcherFunctionWithContext< + Context, + [inlineSnapshot?: string, fromPromise?: boolean] +>; + +export declare const toThrowErrorMatchingSnapshot: MatcherFunctionWithContext< + Context, + [hint?: string, fromPromise?: boolean] +>; + +export {}; diff --git a/node_modules/jest-snapshot/build/index.js b/node_modules/jest-snapshot/build/index.js new file mode 100644 index 0000000..f459e3f --- /dev/null +++ b/node_modules/jest-snapshot/build/index.js @@ -0,0 +1,583 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'EXTENSION', { + enumerable: true, + get: function () { + return _SnapshotResolver.EXTENSION; + } +}); +Object.defineProperty(exports, 'SnapshotState', { + enumerable: true, + get: function () { + return _State.default; + } +}); +Object.defineProperty(exports, 'addSerializer', { + enumerable: true, + get: function () { + return _plugins.addSerializer; + } +}); +Object.defineProperty(exports, 'buildSnapshotResolver', { + enumerable: true, + get: function () { + return _SnapshotResolver.buildSnapshotResolver; + } +}); +exports.cleanup = void 0; +Object.defineProperty(exports, 'getSerializers', { + enumerable: true, + get: function () { + return _plugins.getSerializers; + } +}); +Object.defineProperty(exports, 'isSnapshotPath', { + enumerable: true, + get: function () { + return _SnapshotResolver.isSnapshotPath; + } +}); +exports.toThrowErrorMatchingSnapshot = + exports.toThrowErrorMatchingInlineSnapshot = + exports.toMatchSnapshot = + exports.toMatchInlineSnapshot = + void 0; +var fs = _interopRequireWildcard(require('graceful-fs')); +var _jestMatcherUtils = require('jest-matcher-utils'); +var _SnapshotResolver = require('./SnapshotResolver'); +var _printSnapshot = require('./printSnapshot'); +var _utils = require('./utils'); +var _plugins = require('./plugins'); +var _State = _interopRequireDefault(require('./State')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestExistsFile = + globalThis[Symbol.for('jest-native-exists-file')] || fs.existsSync; +const DID_NOT_THROW = 'Received function did not throw'; // same as toThrow +const NOT_SNAPSHOT_MATCHERS = `Snapshot matchers cannot be used with ${(0, +_jestMatcherUtils.BOLD_WEIGHT)('not')}`; +const INDENTATION_REGEX = /^([^\S\n]*)\S/m; + +// Display name in report when matcher fails same as in snapshot file, +// but with optional hint argument in bold weight. +const printSnapshotName = (concatenatedBlockNames = '', hint = '', count) => { + const hasNames = concatenatedBlockNames.length !== 0; + const hasHint = hint.length !== 0; + return `Snapshot name: \`${ + hasNames ? (0, _utils.escapeBacktickString)(concatenatedBlockNames) : '' + }${hasNames && hasHint ? ': ' : ''}${ + hasHint + ? (0, _jestMatcherUtils.BOLD_WEIGHT)( + (0, _utils.escapeBacktickString)(hint) + ) + : '' + } ${count}\``; +}; +function stripAddedIndentation(inlineSnapshot) { + // Find indentation if exists. + const match = inlineSnapshot.match(INDENTATION_REGEX); + if (!match || !match[1]) { + // No indentation. + return inlineSnapshot; + } + const indentation = match[1]; + const lines = inlineSnapshot.split('\n'); + if (lines.length <= 2) { + // Must be at least 3 lines. + return inlineSnapshot; + } + if (lines[0].trim() !== '' || lines[lines.length - 1].trim() !== '') { + // If not blank first and last lines, abort. + return inlineSnapshot; + } + for (let i = 1; i < lines.length - 1; i++) { + if (lines[i] !== '') { + if (lines[i].indexOf(indentation) !== 0) { + // All lines except first and last should either be blank or have the same + // indent as the first line (or more). If this isn't the case we don't + // want to touch the snapshot at all. + return inlineSnapshot; + } + lines[i] = lines[i].substring(indentation.length); + } + } + + // Last line is a special case because it won't have the same indent as others + // but may still have been given some indent to line up. + lines[lines.length - 1] = ''; + + // Return inline snapshot, now at indent 0. + inlineSnapshot = lines.join('\n'); + return inlineSnapshot; +} +const fileExists = (filePath, hasteFS) => + hasteFS.exists(filePath) || jestExistsFile(filePath); +const cleanup = (hasteFS, update, snapshotResolver, testPathIgnorePatterns) => { + const pattern = `\\.${_SnapshotResolver.EXTENSION}$`; + const files = hasteFS.matchFiles(pattern); + let testIgnorePatternsRegex = null; + if (testPathIgnorePatterns && testPathIgnorePatterns.length > 0) { + testIgnorePatternsRegex = new RegExp(testPathIgnorePatterns.join('|')); + } + const list = files.filter(snapshotFile => { + const testPath = snapshotResolver.resolveTestPath(snapshotFile); + + // ignore snapshots of ignored tests + if (testIgnorePatternsRegex && testIgnorePatternsRegex.test(testPath)) { + return false; + } + if (!fileExists(testPath, hasteFS)) { + if (update === 'all') { + fs.unlinkSync(snapshotFile); + } + return true; + } + return false; + }); + return { + filesRemoved: list.length, + filesRemovedList: list + }; +}; +exports.cleanup = cleanup; +const toMatchSnapshot = function (received, propertiesOrHint, hint) { + const matcherName = 'toMatchSnapshot'; + let properties; + const length = arguments.length; + if (length === 2 && typeof propertiesOrHint === 'string') { + hint = propertiesOrHint; + } else if (length >= 2) { + if ( + Array.isArray(propertiesOrHint) || + typeof propertiesOrHint !== 'object' || + propertiesOrHint === null + ) { + const options = { + isNot: this.isNot, + promise: this.promise + }; + let printedWithType = (0, _jestMatcherUtils.printWithType)( + 'Expected properties', + propertiesOrHint, + _printSnapshot.printExpected + ); + if (length === 3) { + options.secondArgument = 'hint'; + options.secondArgumentColor = _jestMatcherUtils.BOLD_WEIGHT; + if (propertiesOrHint == null) { + printedWithType += + "\n\nTo provide a hint without properties: toMatchSnapshot('hint')"; + } + } + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + _printSnapshot.PROPERTIES_ARG, + options + ), + `Expected ${(0, _jestMatcherUtils.EXPECTED_COLOR)( + 'properties' + )} must be an object`, + printedWithType + ) + ); + } + + // Future breaking change: Snapshot hint must be a string + // if (arguments.length === 3 && typeof hint !== 'string') {} + + properties = propertiesOrHint; + } + return _toMatchSnapshot({ + context: this, + hint, + isInline: false, + matcherName, + properties, + received + }); +}; +exports.toMatchSnapshot = toMatchSnapshot; +const toMatchInlineSnapshot = function ( + received, + propertiesOrSnapshot, + inlineSnapshot +) { + const matcherName = 'toMatchInlineSnapshot'; + let properties; + const length = arguments.length; + if (length === 2 && typeof propertiesOrSnapshot === 'string') { + inlineSnapshot = propertiesOrSnapshot; + } else if (length >= 2) { + const options = { + isNot: this.isNot, + promise: this.promise + }; + if (length === 3) { + options.secondArgument = _printSnapshot.SNAPSHOT_ARG; + options.secondArgumentColor = _printSnapshot.noColor; + } + if ( + Array.isArray(propertiesOrSnapshot) || + typeof propertiesOrSnapshot !== 'object' || + propertiesOrSnapshot === null + ) { + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + _printSnapshot.PROPERTIES_ARG, + options + ), + `Expected ${(0, _jestMatcherUtils.EXPECTED_COLOR)( + 'properties' + )} must be an object`, + (0, _jestMatcherUtils.printWithType)( + 'Expected properties', + propertiesOrSnapshot, + _printSnapshot.printExpected + ) + ) + ); + } + if (length === 3 && typeof inlineSnapshot !== 'string') { + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + _printSnapshot.PROPERTIES_ARG, + options + ), + 'Inline snapshot must be a string', + (0, _jestMatcherUtils.printWithType)( + 'Inline snapshot', + inlineSnapshot, + _utils.serialize + ) + ) + ); + } + properties = propertiesOrSnapshot; + } + return _toMatchSnapshot({ + context: this, + inlineSnapshot: + inlineSnapshot !== undefined + ? stripAddedIndentation(inlineSnapshot) + : undefined, + isInline: true, + matcherName, + properties, + received + }); +}; +exports.toMatchInlineSnapshot = toMatchInlineSnapshot; +const _toMatchSnapshot = config => { + const {context, hint, inlineSnapshot, isInline, matcherName, properties} = + config; + let {received} = config; + context.dontThrow && context.dontThrow(); + const {currentTestName, isNot, snapshotState} = context; + if (isNot) { + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _printSnapshot.matcherHintFromConfig)(config, false), + NOT_SNAPSHOT_MATCHERS + ) + ); + } + if (snapshotState == null) { + // Because the state is the problem, this is not a matcher error. + // Call generic stringify from jest-matcher-utils package + // because uninitialized snapshot state does not need snapshot serializers. + throw new Error( + `${(0, _printSnapshot.matcherHintFromConfig)(config, false)}\n\n` + + 'Snapshot state must be initialized' + + `\n\n${(0, _jestMatcherUtils.printWithType)( + 'Snapshot state', + snapshotState, + _jestMatcherUtils.stringify + )}` + ); + } + const fullTestName = + currentTestName && hint + ? `${currentTestName}: ${hint}` + : currentTestName || ''; // future BREAKING change: || hint + + if (typeof properties === 'object') { + if (typeof received !== 'object' || received === null) { + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _printSnapshot.matcherHintFromConfig)(config, false), + `${(0, _jestMatcherUtils.RECEIVED_COLOR)( + 'received' + )} value must be an object when the matcher has ${(0, + _jestMatcherUtils.EXPECTED_COLOR)('properties')}`, + (0, _jestMatcherUtils.printWithType)( + 'Received', + received, + _printSnapshot.printReceived + ) + ) + ); + } + const propertyPass = context.equals(received, properties, [ + context.utils.iterableEquality, + context.utils.subsetEquality + ]); + if (!propertyPass) { + const key = snapshotState.fail(fullTestName, received); + const matched = /(\d+)$/.exec(key); + const count = matched === null ? 1 : Number(matched[1]); + const message = () => + `${(0, _printSnapshot.matcherHintFromConfig)( + config, + false + )}\n\n${printSnapshotName(currentTestName, hint, count)}\n\n${(0, + _printSnapshot.printPropertiesAndReceived)( + properties, + received, + snapshotState.expand + )}`; + return { + message, + name: matcherName, + pass: false + }; + } else { + received = (0, _utils.deepMerge)(received, properties); + } + } + const result = snapshotState.match({ + error: context.error, + inlineSnapshot, + isInline, + received, + testName: fullTestName + }); + const {actual, count, expected, pass} = result; + if (pass) { + return { + message: () => '', + pass: true + }; + } + const message = + expected === undefined + ? () => + `${(0, _printSnapshot.matcherHintFromConfig)( + config, + true + )}\n\n${printSnapshotName(currentTestName, hint, count)}\n\n` + + `New snapshot was ${(0, _jestMatcherUtils.BOLD_WEIGHT)( + 'not written' + )}. The update flag ` + + 'must be explicitly passed to write a new snapshot.\n\n' + + 'This is likely because this test is run in a continuous integration ' + + '(CI) environment in which snapshots are not written by default.\n\n' + + `Received:${actual.includes('\n') ? '\n' : ' '}${(0, + _printSnapshot.bReceivedColor)(actual)}` + : () => + `${(0, _printSnapshot.matcherHintFromConfig)( + config, + true + )}\n\n${printSnapshotName(currentTestName, hint, count)}\n\n${(0, + _printSnapshot.printSnapshotAndReceived)( + expected, + actual, + received, + snapshotState.expand, + snapshotState.snapshotFormat + )}`; + + // Passing the actual and expected objects so that a custom reporter + // could access them, for example in order to display a custom visual diff, + // or create a different error message + return { + actual, + expected, + message, + name: matcherName, + pass: false + }; +}; +const toThrowErrorMatchingSnapshot = function (received, hint, fromPromise) { + const matcherName = 'toThrowErrorMatchingSnapshot'; + + // Future breaking change: Snapshot hint must be a string + // if (hint !== undefined && typeof hint !== string) {} + + return _toThrowErrorMatchingSnapshot( + { + context: this, + hint, + isInline: false, + matcherName, + received + }, + fromPromise + ); +}; +exports.toThrowErrorMatchingSnapshot = toThrowErrorMatchingSnapshot; +const toThrowErrorMatchingInlineSnapshot = function ( + received, + inlineSnapshot, + fromPromise +) { + const matcherName = 'toThrowErrorMatchingInlineSnapshot'; + if (inlineSnapshot !== undefined && typeof inlineSnapshot !== 'string') { + const options = { + expectedColor: _printSnapshot.noColor, + isNot: this.isNot, + promise: this.promise + }; + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + _printSnapshot.SNAPSHOT_ARG, + options + ), + 'Inline snapshot must be a string', + (0, _jestMatcherUtils.printWithType)( + 'Inline snapshot', + inlineSnapshot, + _utils.serialize + ) + ) + ); + } + return _toThrowErrorMatchingSnapshot( + { + context: this, + inlineSnapshot: + inlineSnapshot !== undefined + ? stripAddedIndentation(inlineSnapshot) + : undefined, + isInline: true, + matcherName, + received + }, + fromPromise + ); +}; +exports.toThrowErrorMatchingInlineSnapshot = toThrowErrorMatchingInlineSnapshot; +const _toThrowErrorMatchingSnapshot = (config, fromPromise) => { + const {context, hint, inlineSnapshot, isInline, matcherName, received} = + config; + context.dontThrow && context.dontThrow(); + const {isNot, promise} = context; + if (!fromPromise) { + if (typeof received !== 'function') { + const options = { + isNot, + promise + }; + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + '', + options + ), + `${(0, _jestMatcherUtils.RECEIVED_COLOR)( + 'received' + )} value must be a function`, + (0, _jestMatcherUtils.printWithType)( + 'Received', + received, + _printSnapshot.printReceived + ) + ) + ); + } + } + if (isNot) { + throw new Error( + (0, _jestMatcherUtils.matcherErrorMessage)( + (0, _printSnapshot.matcherHintFromConfig)(config, false), + NOT_SNAPSHOT_MATCHERS + ) + ); + } + let error; + if (fromPromise) { + error = received; + } else { + try { + received(); + } catch (e) { + error = e; + } + } + if (error === undefined) { + // Because the received value is a function, this is not a matcher error. + throw new Error( + `${(0, _printSnapshot.matcherHintFromConfig)( + config, + false + )}\n\n${DID_NOT_THROW}` + ); + } + return _toMatchSnapshot({ + context, + hint, + inlineSnapshot, + isInline, + matcherName, + received: error.message + }); +}; diff --git a/node_modules/jest-snapshot/build/mockSerializer.js b/node_modules/jest-snapshot/build/mockSerializer.js new file mode 100644 index 0000000..e6b6fd4 --- /dev/null +++ b/node_modules/jest-snapshot/build/mockSerializer.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.test = exports.serialize = exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const serialize = (val, config, indentation, depth, refs, printer) => { + // Serialize a non-default name, even if config.printFunctionName is false. + const name = val.getMockName(); + const nameString = name === 'jest.fn()' ? '' : ` ${name}`; + let callsString = ''; + if (val.mock.calls.length !== 0) { + const indentationNext = indentation + config.indent; + callsString = ` {${config.spacingOuter}${indentationNext}"calls": ${printer( + val.mock.calls, + config, + indentationNext, + depth, + refs + )}${config.min ? ', ' : ','}${ + config.spacingOuter + }${indentationNext}"results": ${printer( + val.mock.results, + config, + indentationNext, + depth, + refs + )}${config.min ? '' : ','}${config.spacingOuter}${indentation}}`; + } + return `[MockFunction${nameString}]${callsString}`; +}; +exports.serialize = serialize; +const test = val => val && !!val._isMockFunction; +exports.test = test; +const plugin = { + serialize, + test +}; +var _default = plugin; +exports.default = _default; diff --git a/node_modules/jest-snapshot/build/plugins.js b/node_modules/jest-snapshot/build/plugins.js new file mode 100644 index 0000000..6dc79dc --- /dev/null +++ b/node_modules/jest-snapshot/build/plugins.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getSerializers = exports.addSerializer = void 0; +var _prettyFormat = require('pretty-format'); +var _mockSerializer = _interopRequireDefault(require('./mockSerializer')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const { + DOMCollection, + DOMElement, + Immutable, + ReactElement, + ReactTestComponent, + AsymmetricMatcher +} = _prettyFormat.plugins; +let PLUGINS = [ + ReactTestComponent, + ReactElement, + DOMElement, + DOMCollection, + Immutable, + _mockSerializer.default, + AsymmetricMatcher +]; + +// Prepend to list so the last added is the first tested. +const addSerializer = plugin => { + PLUGINS = [plugin].concat(PLUGINS); +}; +exports.addSerializer = addSerializer; +const getSerializers = () => PLUGINS; +exports.getSerializers = getSerializers; diff --git a/node_modules/jest-snapshot/build/printSnapshot.js b/node_modules/jest-snapshot/build/printSnapshot.js new file mode 100644 index 0000000..bdfe447 --- /dev/null +++ b/node_modules/jest-snapshot/build/printSnapshot.js @@ -0,0 +1,340 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printSnapshotAndReceived = + exports.printReceived = + exports.printPropertiesAndReceived = + exports.printExpected = + exports.noColor = + exports.matcherHintFromConfig = + exports.getSnapshotColorForChalkInstance = + exports.getReceivedColorForChalkInstance = + exports.bReceivedColor = + exports.aSnapshotColor = + exports.SNAPSHOT_ARG = + exports.PROPERTIES_ARG = + exports.HINT_ARG = + void 0; +var _chalk = _interopRequireDefault(require('chalk')); +var _expectUtils = require('@jest/expect-utils'); +var _jestDiff = require('jest-diff'); +var _jestGetType = require('jest-get-type'); +var _jestMatcherUtils = require('jest-matcher-utils'); +var _prettyFormat = require('pretty-format'); +var _colors = require('./colors'); +var _dedentLines = require('./dedentLines'); +var _utils = require('./utils'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const getSnapshotColorForChalkInstance = chalkInstance => { + const level = chalkInstance.level; + if (level === 3) { + return chalkInstance + .rgb( + _colors.aForeground3[0], + _colors.aForeground3[1], + _colors.aForeground3[2] + ) + .bgRgb( + _colors.aBackground3[0], + _colors.aBackground3[1], + _colors.aBackground3[2] + ); + } + if (level === 2) { + return chalkInstance + .ansi256(_colors.aForeground2) + .bgAnsi256(_colors.aBackground2); + } + return chalkInstance.magenta.bgYellowBright; +}; +exports.getSnapshotColorForChalkInstance = getSnapshotColorForChalkInstance; +const getReceivedColorForChalkInstance = chalkInstance => { + const level = chalkInstance.level; + if (level === 3) { + return chalkInstance + .rgb( + _colors.bForeground3[0], + _colors.bForeground3[1], + _colors.bForeground3[2] + ) + .bgRgb( + _colors.bBackground3[0], + _colors.bBackground3[1], + _colors.bBackground3[2] + ); + } + if (level === 2) { + return chalkInstance + .ansi256(_colors.bForeground2) + .bgAnsi256(_colors.bBackground2); + } + return chalkInstance.cyan.bgWhiteBright; // also known as teal +}; +exports.getReceivedColorForChalkInstance = getReceivedColorForChalkInstance; +const aSnapshotColor = getSnapshotColorForChalkInstance(_chalk.default); +exports.aSnapshotColor = aSnapshotColor; +const bReceivedColor = getReceivedColorForChalkInstance(_chalk.default); +exports.bReceivedColor = bReceivedColor; +const noColor = string => string; +exports.noColor = noColor; +const HINT_ARG = 'hint'; +exports.HINT_ARG = HINT_ARG; +const SNAPSHOT_ARG = 'snapshot'; +exports.SNAPSHOT_ARG = SNAPSHOT_ARG; +const PROPERTIES_ARG = 'properties'; +exports.PROPERTIES_ARG = PROPERTIES_ARG; +const matcherHintFromConfig = ( + {context: {isNot, promise}, hint, inlineSnapshot, matcherName, properties}, + isUpdatable +) => { + const options = { + isNot, + promise + }; + if (isUpdatable) { + options.receivedColor = bReceivedColor; + } + let expectedArgument = ''; + if (typeof properties === 'object') { + expectedArgument = PROPERTIES_ARG; + if (isUpdatable) { + options.expectedColor = noColor; + } + if (typeof hint === 'string' && hint.length !== 0) { + options.secondArgument = HINT_ARG; + options.secondArgumentColor = _jestMatcherUtils.BOLD_WEIGHT; + } else if (typeof inlineSnapshot === 'string') { + options.secondArgument = SNAPSHOT_ARG; + if (isUpdatable) { + options.secondArgumentColor = aSnapshotColor; + } else { + options.secondArgumentColor = noColor; + } + } + } else { + if (typeof hint === 'string' && hint.length !== 0) { + expectedArgument = HINT_ARG; + options.expectedColor = _jestMatcherUtils.BOLD_WEIGHT; + } else if (typeof inlineSnapshot === 'string') { + expectedArgument = SNAPSHOT_ARG; + if (isUpdatable) { + options.expectedColor = aSnapshotColor; + } + } + } + return (0, _jestMatcherUtils.matcherHint)( + matcherName, + undefined, + expectedArgument, + options + ); +}; + +// Given array of diffs, return string: +// * include common substrings +// * exclude change substrings which have opposite op +// * include change substrings which have argument op +// with change color only if there is a common substring +exports.matcherHintFromConfig = matcherHintFromConfig; +const joinDiffs = (diffs, op, hasCommon) => + diffs.reduce( + (reduced, diff) => + reduced + + (diff[0] === _jestDiff.DIFF_EQUAL + ? diff[1] + : diff[0] !== op + ? '' + : hasCommon + ? (0, _jestMatcherUtils.INVERTED_COLOR)(diff[1]) + : diff[1]), + '' + ); +const isLineDiffable = received => { + const receivedType = (0, _jestGetType.getType)(received); + if ((0, _jestGetType.isPrimitive)(received)) { + return typeof received === 'string'; + } + if ( + receivedType === 'date' || + receivedType === 'function' || + receivedType === 'regexp' + ) { + return false; + } + if (received instanceof Error) { + return false; + } + if ( + receivedType === 'object' && + typeof received.asymmetricMatch === 'function' + ) { + return false; + } + return true; +}; +const printExpected = val => + (0, _jestMatcherUtils.EXPECTED_COLOR)((0, _utils.minify)(val)); +exports.printExpected = printExpected; +const printReceived = val => + (0, _jestMatcherUtils.RECEIVED_COLOR)((0, _utils.minify)(val)); +exports.printReceived = printReceived; +const printPropertiesAndReceived = ( + properties, + received, + expand // CLI options: true if `--expand` or false if `--no-expand` +) => { + const aAnnotation = 'Expected properties'; + const bAnnotation = 'Received value'; + if (isLineDiffable(properties) && isLineDiffable(received)) { + const {replacedExpected, replacedReceived} = (0, + _jestMatcherUtils.replaceMatchedToAsymmetricMatcher)( + properties, + received, + [], + [] + ); + return (0, _jestDiff.diffLinesUnified)( + (0, _utils.serialize)(replacedExpected).split('\n'), + (0, _utils.serialize)( + (0, _expectUtils.getObjectSubset)(replacedReceived, replacedExpected) + ).split('\n'), + { + aAnnotation, + aColor: _jestMatcherUtils.EXPECTED_COLOR, + bAnnotation, + bColor: _jestMatcherUtils.RECEIVED_COLOR, + changeLineTrailingSpaceColor: _chalk.default.bgYellow, + commonLineTrailingSpaceColor: _chalk.default.bgYellow, + emptyFirstOrLastLinePlaceholder: '↵', + // U+21B5 + expand, + includeChangeCounts: true + } + ); + } + const printLabel = (0, _jestMatcherUtils.getLabelPrinter)( + aAnnotation, + bAnnotation + ); + return `${printLabel(aAnnotation) + printExpected(properties)}\n${printLabel( + bAnnotation + )}${printReceived(received)}`; +}; +exports.printPropertiesAndReceived = printPropertiesAndReceived; +const MAX_DIFF_STRING_LENGTH = 20000; +const printSnapshotAndReceived = (a, b, received, expand, snapshotFormat) => { + const aAnnotation = 'Snapshot'; + const bAnnotation = 'Received'; + const aColor = aSnapshotColor; + const bColor = bReceivedColor; + const options = { + aAnnotation, + aColor, + bAnnotation, + bColor, + changeLineTrailingSpaceColor: noColor, + commonLineTrailingSpaceColor: _chalk.default.bgYellow, + emptyFirstOrLastLinePlaceholder: '↵', + // U+21B5 + expand, + includeChangeCounts: true + }; + if (typeof received === 'string') { + if ( + a.length >= 2 && + a.startsWith('"') && + a.endsWith('"') && + b === (0, _prettyFormat.format)(received) + ) { + // If snapshot looks like default serialization of a string + // and received is string which has default serialization. + + if (!a.includes('\n') && !b.includes('\n')) { + // If neither string is multiline, + // display as labels and quoted strings. + let aQuoted = a; + let bQuoted = b; + if ( + a.length - 2 <= MAX_DIFF_STRING_LENGTH && + b.length - 2 <= MAX_DIFF_STRING_LENGTH + ) { + const diffs = (0, _jestDiff.diffStringsRaw)( + a.slice(1, -1), + b.slice(1, -1), + true + ); + const hasCommon = diffs.some( + diff => diff[0] === _jestDiff.DIFF_EQUAL + ); + aQuoted = `"${joinDiffs(diffs, _jestDiff.DIFF_DELETE, hasCommon)}"`; + bQuoted = `"${joinDiffs(diffs, _jestDiff.DIFF_INSERT, hasCommon)}"`; + } + const printLabel = (0, _jestMatcherUtils.getLabelPrinter)( + aAnnotation, + bAnnotation + ); + return `${printLabel(aAnnotation) + aColor(aQuoted)}\n${printLabel( + bAnnotation + )}${bColor(bQuoted)}`; + } + + // Else either string is multiline, so display as unquoted strings. + a = (0, _utils.deserializeString)(a); // hypothetical expected string + b = received; // not serialized + } + // Else expected had custom serialization or was not a string + // or received has custom serialization. + + return a.length <= MAX_DIFF_STRING_LENGTH && + b.length <= MAX_DIFF_STRING_LENGTH + ? (0, _jestDiff.diffStringsUnified)(a, b, options) + : (0, _jestDiff.diffLinesUnified)(a.split('\n'), b.split('\n'), options); + } + if (isLineDiffable(received)) { + const aLines2 = a.split('\n'); + const bLines2 = b.split('\n'); + + // Fall through to fix a regression for custom serializers + // like jest-snapshot-serializer-raw that ignore the indent option. + const b0 = (0, _utils.serialize)(received, 0, snapshotFormat); + if (b0 !== b) { + const aLines0 = (0, _dedentLines.dedentLines)(aLines2); + if (aLines0 !== null) { + // Compare lines without indentation. + const bLines0 = b0.split('\n'); + return (0, _jestDiff.diffLinesUnified2)( + aLines2, + bLines2, + aLines0, + bLines0, + options + ); + } + } + + // Fall back because: + // * props include a multiline string + // * text has more than one adjacent line + // * markup does not close + return (0, _jestDiff.diffLinesUnified)(aLines2, bLines2, options); + } + const printLabel = (0, _jestMatcherUtils.getLabelPrinter)( + aAnnotation, + bAnnotation + ); + return `${printLabel(aAnnotation) + aColor(a)}\n${printLabel( + bAnnotation + )}${bColor(b)}`; +}; +exports.printSnapshotAndReceived = printSnapshotAndReceived; diff --git a/node_modules/jest-snapshot/build/types.js b/node_modules/jest-snapshot/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-snapshot/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-snapshot/build/utils.js b/node_modules/jest-snapshot/build/utils.js new file mode 100644 index 0000000..1baa6b9 --- /dev/null +++ b/node_modules/jest-snapshot/build/utils.js @@ -0,0 +1,310 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.testNameToKey = + exports.serialize = + exports.saveSnapshotFile = + exports.removeLinesBeforeExternalMatcherTrap = + exports.removeExtraLineBreaks = + exports.minify = + exports.keyToTestName = + exports.getSnapshotData = + exports.escapeBacktickString = + exports.ensureDirectoryExists = + exports.deserializeString = + exports.deepMerge = + exports.addExtraLineBreaks = + exports.SNAPSHOT_VERSION_WARNING = + exports.SNAPSHOT_VERSION = + exports.SNAPSHOT_GUIDE_LINK = + void 0; +var path = _interopRequireWildcard(require('path')); +var _chalk = _interopRequireDefault(require('chalk')); +var fs = _interopRequireWildcard(require('graceful-fs')); +var _naturalCompare = _interopRequireDefault(require('natural-compare')); +var _prettyFormat = require('pretty-format'); +var _plugins = require('./plugins'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestWriteFile = + globalThis[Symbol.for('jest-native-write-file')] || fs.writeFileSync; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestReadFile = + globalThis[Symbol.for('jest-native-read-file')] || fs.readFileSync; +var Symbol = globalThis['jest-symbol-do-not-touch'] || globalThis.Symbol; +var jestExistsFile = + globalThis[Symbol.for('jest-native-exists-file')] || fs.existsSync; +const SNAPSHOT_VERSION = '1'; +exports.SNAPSHOT_VERSION = SNAPSHOT_VERSION; +const SNAPSHOT_VERSION_REGEXP = /^\/\/ Jest Snapshot v(.+),/; +const SNAPSHOT_GUIDE_LINK = 'https://goo.gl/fbAQLP'; +exports.SNAPSHOT_GUIDE_LINK = SNAPSHOT_GUIDE_LINK; +const SNAPSHOT_VERSION_WARNING = _chalk.default.yellow( + `${_chalk.default.bold('Warning')}: Before you upgrade snapshots, ` + + 'we recommend that you revert any local changes to tests or other code, ' + + 'to ensure that you do not store invalid state.' +); +exports.SNAPSHOT_VERSION_WARNING = SNAPSHOT_VERSION_WARNING; +const writeSnapshotVersion = () => + `// Jest Snapshot v${SNAPSHOT_VERSION}, ${SNAPSHOT_GUIDE_LINK}`; +const validateSnapshotVersion = snapshotContents => { + const versionTest = SNAPSHOT_VERSION_REGEXP.exec(snapshotContents); + const version = versionTest && versionTest[1]; + if (!version) { + return new Error( + _chalk.default.red( + `${_chalk.default.bold( + 'Outdated snapshot' + )}: No snapshot header found. ` + + 'Jest 19 introduced versioned snapshots to ensure all developers ' + + 'on a project are using the same version of Jest. ' + + 'Please update all snapshots during this upgrade of Jest.\n\n' + ) + SNAPSHOT_VERSION_WARNING + ); + } + if (version < SNAPSHOT_VERSION) { + return new Error( + // eslint-disable-next-line prefer-template + _chalk.default.red( + `${_chalk.default.red.bold( + 'Outdated snapshot' + )}: The version of the snapshot ` + + 'file associated with this test is outdated. The snapshot file ' + + 'version ensures that all developers on a project are using ' + + 'the same version of Jest. ' + + 'Please update all snapshots during this upgrade of Jest.' + ) + + '\n\n' + + `Expected: v${SNAPSHOT_VERSION}\n` + + `Received: v${version}\n\n` + + SNAPSHOT_VERSION_WARNING + ); + } + if (version > SNAPSHOT_VERSION) { + return new Error( + // eslint-disable-next-line prefer-template + _chalk.default.red( + `${_chalk.default.red.bold( + 'Outdated Jest version' + )}: The version of this ` + + 'snapshot file indicates that this project is meant to be used ' + + 'with a newer version of Jest. The snapshot file version ensures ' + + 'that all developers on a project are using the same version of ' + + 'Jest. Please update your version of Jest and re-run the tests.' + ) + + '\n\n' + + `Expected: v${SNAPSHOT_VERSION}\n` + + `Received: v${version}` + ); + } + return null; +}; +function isObject(item) { + return item != null && typeof item === 'object' && !Array.isArray(item); +} +const testNameToKey = (testName, count) => `${testName} ${count}`; +exports.testNameToKey = testNameToKey; +const keyToTestName = key => { + if (!/ \d+$/.test(key)) { + throw new Error('Snapshot keys must end with a number.'); + } + return key.replace(/ \d+$/, ''); +}; +exports.keyToTestName = keyToTestName; +const getSnapshotData = (snapshotPath, update) => { + const data = Object.create(null); + let snapshotContents = ''; + let dirty = false; + if (jestExistsFile(snapshotPath)) { + try { + snapshotContents = jestReadFile(snapshotPath, 'utf8'); + // eslint-disable-next-line no-new-func + const populate = new Function('exports', snapshotContents); + populate(data); + } catch {} + } + const validationResult = validateSnapshotVersion(snapshotContents); + const isInvalid = snapshotContents && validationResult; + if (update === 'none' && isInvalid) { + throw validationResult; + } + if ((update === 'all' || update === 'new') && isInvalid) { + dirty = true; + } + return { + data, + dirty + }; +}; + +// Add extra line breaks at beginning and end of multiline snapshot +// to make the content easier to read. +exports.getSnapshotData = getSnapshotData; +const addExtraLineBreaks = string => + string.includes('\n') ? `\n${string}\n` : string; + +// Remove extra line breaks at beginning and end of multiline snapshot. +// Instead of trim, which can remove additional newlines or spaces +// at beginning or end of the content from a custom serializer. +exports.addExtraLineBreaks = addExtraLineBreaks; +const removeExtraLineBreaks = string => + string.length > 2 && string.startsWith('\n') && string.endsWith('\n') + ? string.slice(1, -1) + : string; +exports.removeExtraLineBreaks = removeExtraLineBreaks; +const removeLinesBeforeExternalMatcherTrap = stack => { + const lines = stack.split('\n'); + for (let i = 0; i < lines.length; i += 1) { + // It's a function name specified in `packages/expect/src/index.ts` + // for external custom matchers. + if (lines[i].includes('__EXTERNAL_MATCHER_TRAP__')) { + return lines.slice(i + 1).join('\n'); + } + } + return stack; +}; +exports.removeLinesBeforeExternalMatcherTrap = + removeLinesBeforeExternalMatcherTrap; +const escapeRegex = true; +const printFunctionName = false; +const serialize = (val, indent = 2, formatOverrides = {}) => + normalizeNewlines( + (0, _prettyFormat.format)(val, { + escapeRegex, + indent, + plugins: (0, _plugins.getSerializers)(), + printFunctionName, + ...formatOverrides + }) + ); +exports.serialize = serialize; +const minify = val => + (0, _prettyFormat.format)(val, { + escapeRegex, + min: true, + plugins: (0, _plugins.getSerializers)(), + printFunctionName + }); + +// Remove double quote marks and unescape double quotes and backslashes. +exports.minify = minify; +const deserializeString = stringified => + stringified.slice(1, -1).replace(/\\("|\\)/g, '$1'); +exports.deserializeString = deserializeString; +const escapeBacktickString = str => str.replace(/`|\\|\${/g, '\\$&'); +exports.escapeBacktickString = escapeBacktickString; +const printBacktickString = str => `\`${escapeBacktickString(str)}\``; +const ensureDirectoryExists = filePath => { + try { + fs.mkdirSync(path.join(path.dirname(filePath)), { + recursive: true + }); + } catch {} +}; +exports.ensureDirectoryExists = ensureDirectoryExists; +const normalizeNewlines = string => string.replace(/\r\n|\r/g, '\n'); +const saveSnapshotFile = (snapshotData, snapshotPath) => { + const snapshots = Object.keys(snapshotData) + .sort(_naturalCompare.default) + .map( + key => + `exports[${printBacktickString(key)}] = ${printBacktickString( + normalizeNewlines(snapshotData[key]) + )};` + ); + ensureDirectoryExists(snapshotPath); + jestWriteFile( + snapshotPath, + `${writeSnapshotVersion()}\n\n${snapshots.join('\n\n')}\n` + ); +}; +exports.saveSnapshotFile = saveSnapshotFile; +const deepMergeArray = (target, source) => { + const mergedOutput = Array.from(target); + source.forEach((sourceElement, index) => { + const targetElement = mergedOutput[index]; + if (Array.isArray(target[index])) { + mergedOutput[index] = deepMergeArray(target[index], sourceElement); + } else if (isObject(targetElement)) { + mergedOutput[index] = deepMerge(target[index], sourceElement); + } else { + // Source does not exist in target or target is primitive and cannot be deep merged + mergedOutput[index] = sourceElement; + } + }); + return mergedOutput; +}; + +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +const deepMerge = (target, source) => { + if (isObject(target) && isObject(source)) { + const mergedOutput = { + ...target + }; + Object.keys(source).forEach(key => { + if (isObject(source[key]) && !source[key].$$typeof) { + if (!(key in target)) + Object.assign(mergedOutput, { + [key]: source[key] + }); + else mergedOutput[key] = deepMerge(target[key], source[key]); + } else if (Array.isArray(source[key])) { + mergedOutput[key] = deepMergeArray(target[key], source[key]); + } else { + Object.assign(mergedOutput, { + [key]: source[key] + }); + } + }); + return mergedOutput; + } else if (Array.isArray(target) && Array.isArray(source)) { + return deepMergeArray(target, source); + } + return target; +}; +exports.deepMerge = deepMerge; diff --git a/node_modules/jest-snapshot/node_modules/.bin/semver b/node_modules/jest-snapshot/node_modules/.bin/semver new file mode 100644 index 0000000..77443e7 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/.bin/semver @@ -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/../semver/bin/semver.js" "$@" +else + exec node "$basedir/../semver/bin/semver.js" "$@" +fi diff --git a/node_modules/jest-snapshot/node_modules/.bin/semver.cmd b/node_modules/jest-snapshot/node_modules/.bin/semver.cmd new file mode 100644 index 0000000..9913fa9 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/.bin/semver.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%\..\semver\bin\semver.js" %* diff --git a/node_modules/jest-snapshot/node_modules/.bin/semver.ps1 b/node_modules/jest-snapshot/node_modules/.bin/semver.ps1 new file mode 100644 index 0000000..314717a --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/.bin/semver.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/../semver/bin/semver.js" $args + } else { + & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../semver/bin/semver.js" $args + } else { + & "node$exe" "$basedir/../semver/bin/semver.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/jest-snapshot/node_modules/semver/LICENSE b/node_modules/jest-snapshot/node_modules/semver/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/LICENSE @@ -0,0 +1,15 @@ +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. diff --git a/node_modules/jest-snapshot/node_modules/semver/README.md b/node_modules/jest-snapshot/node_modules/semver/README.md new file mode 100644 index 0000000..df54e7a --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/README.md @@ -0,0 +1,568 @@ +semver(1) -- The semantic versioner for npm +=========================================== + +## Install + +```bash +npm install semver +```` + +## Usage + +As a node module: + +```js +const semver = require('semver') + +semver.valid('1.2.3') // '1.2.3' +semver.valid('a.b.c') // null +semver.clean(' =v1.2.3 ') // '1.2.3' +semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true +semver.gt('1.2.3', '9.8.7') // false +semver.lt('1.2.3', '9.8.7') // true +semver.minVersion('>=1.0.0') // '1.0.0' +semver.valid(semver.coerce('v2')) // '2.0.0' +semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' +``` + +You can also just load the module for the function that you care about, if +you'd like to minimize your footprint. + +```js +// load the whole API at once in a single object +const semver = require('semver') + +// or just load the bits you need +// all of them listed here, just pick and choose what you want + +// classes +const SemVer = require('semver/classes/semver') +const Comparator = require('semver/classes/comparator') +const Range = require('semver/classes/range') + +// functions for working with versions +const semverParse = require('semver/functions/parse') +const semverValid = require('semver/functions/valid') +const semverClean = require('semver/functions/clean') +const semverInc = require('semver/functions/inc') +const semverDiff = require('semver/functions/diff') +const semverMajor = require('semver/functions/major') +const semverMinor = require('semver/functions/minor') +const semverPatch = require('semver/functions/patch') +const semverPrerelease = require('semver/functions/prerelease') +const semverCompare = require('semver/functions/compare') +const semverRcompare = require('semver/functions/rcompare') +const semverCompareLoose = require('semver/functions/compare-loose') +const semverCompareBuild = require('semver/functions/compare-build') +const semverSort = require('semver/functions/sort') +const semverRsort = require('semver/functions/rsort') + +// low-level comparators between versions +const semverGt = require('semver/functions/gt') +const semverLt = require('semver/functions/lt') +const semverEq = require('semver/functions/eq') +const semverNeq = require('semver/functions/neq') +const semverGte = require('semver/functions/gte') +const semverLte = require('semver/functions/lte') +const semverCmp = require('semver/functions/cmp') +const semverCoerce = require('semver/functions/coerce') + +// working with ranges +const semverSatisfies = require('semver/functions/satisfies') +const semverMaxSatisfying = require('semver/ranges/max-satisfying') +const semverMinSatisfying = require('semver/ranges/min-satisfying') +const semverToComparators = require('semver/ranges/to-comparators') +const semverMinVersion = require('semver/ranges/min-version') +const semverValidRange = require('semver/ranges/valid') +const semverOutside = require('semver/ranges/outside') +const semverGtr = require('semver/ranges/gtr') +const semverLtr = require('semver/ranges/ltr') +const semverIntersects = require('semver/ranges/intersects') +const simplifyRange = require('semver/ranges/simplify') +const rangeSubset = require('semver/ranges/subset') +``` + +As a command-line utility: + +``` +$ semver -h + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them. +``` + +## Versions + +A "version" is described by the `v2.0.0` specification found at +. + +A leading `"="` or `"v"` character is stripped off and ignored. + +## Ranges + +A `version range` is a set of `comparators` which specify versions +that satisfy the range. + +A `comparator` is composed of an `operator` and a `version`. The set +of primitive `operators` is: + +* `<` Less than +* `<=` Less than or equal to +* `>` Greater than +* `>=` Greater than or equal to +* `=` Equal. If no operator is specified, then equality is assumed, + so this operator is optional, but MAY be included. + +For example, the comparator `>=1.2.7` would match the versions +`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` +or `1.1.0`. + +Comparators can be joined by whitespace to form a `comparator set`, +which is satisfied by the **intersection** of all of the comparators +it includes. + +A range is composed of one or more comparator sets, joined by `||`. A +version matches a range if and only if every comparator in at least +one of the `||`-separated comparator sets is satisfied by the version. + +For example, the range `>=1.2.7 <1.3.0` would match the versions +`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, +or `1.1.0`. + +The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, +`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. + +### Prerelease Tags + +If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then +it will only be allowed to satisfy comparator sets if at least one +comparator with the same `[major, minor, patch]` tuple also has a +prerelease tag. + +For example, the range `>1.2.3-alpha.3` would be allowed to match the +version `1.2.3-alpha.7`, but it would *not* be satisfied by +`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater +than" `1.2.3-alpha.3` according to the SemVer sort rules. The version +range only accepts prerelease tags on the `1.2.3` version. The +version `3.4.5` *would* satisfy the range, because it does not have a +prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. + +The purpose for this behavior is twofold. First, prerelease versions +frequently are updated very quickly, and contain many breaking changes +that are (by the author's design) not yet fit for public consumption. +Therefore, by default, they are excluded from range matching +semantics. + +Second, a user who has opted into using a prerelease version has +clearly indicated the intent to use *that specific* set of +alpha/beta/rc versions. By including a prerelease tag in the range, +the user is indicating that they are aware of the risk. However, it +is still not appropriate to assume that they have opted into taking a +similar risk on the *next* set of prerelease versions. + +Note that this behavior can be suppressed (treating all prerelease +versions as if they were normal versions, for the purpose of range +matching) by setting the `includePrerelease` flag on the options +object to any +[functions](https://github.com/npm/node-semver#functions) that do +range matching. + +#### Prerelease Identifiers + +The method `.inc` takes an additional `identifier` string argument that +will append the value of the string as a prerelease identifier: + +```javascript +semver.inc('1.2.3', 'prerelease', 'beta') +// '1.2.4-beta.0' +``` + +command-line example: + +```bash +$ semver 1.2.3 -i prerelease --preid beta +1.2.4-beta.0 +``` + +Which then can be used to increment further: + +```bash +$ semver 1.2.4-beta.0 -i prerelease +1.2.4-beta.1 +``` + +### Advanced Range Syntax + +Advanced range syntax desugars to primitive comparators in +deterministic ways. + +Advanced ranges may be combined in the same way as primitive +comparators using white space or `||`. + +#### Hyphen Ranges `X.Y.Z - A.B.C` + +Specifies an inclusive set. + +* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` + +If a partial version is provided as the first version in the inclusive +range, then the missing pieces are replaced with zeroes. + +* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` + +If a partial version is provided as the second version in the +inclusive range, then all versions that start with the supplied parts +of the tuple are accepted, but nothing that would be greater than the +provided tuple parts. + +* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` +* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` + +#### X-Ranges `1.2.x` `1.X` `1.2.*` `*` + +Any of `X`, `x`, or `*` may be used to "stand in" for one of the +numeric values in the `[major, minor, patch]` tuple. + +* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless + `includePrerelease` is specified, in which case any version at all + satisfies) +* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) +* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) + +A partial version range is treated as an X-Range, so the special +character is in fact optional. + +* `""` (empty string) := `*` := `>=0.0.0` +* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` +* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` + +#### Tilde Ranges `~1.2.3` `~1.2` `~1` + +Allows patch-level changes if a minor version is specified on the +comparator. Allows minor-level changes if not. + +* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` +* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) +* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) +* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` +* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) +* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) +* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. + +#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` + +Allows changes that do not modify the left-most non-zero element in the +`[major, minor, patch]` tuple. In other words, this allows patch and +minor updates for versions `1.0.0` and above, patch updates for +versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. + +Many authors treat a `0.x` version as if the `x` were the major +"breaking-change" indicator. + +Caret ranges are ideal when an author may make breaking changes +between `0.2.4` and `0.3.0` releases, which is a common practice. +However, it presumes that there will *not* be breaking changes between +`0.2.4` and `0.2.5`. It allows for changes that are presumed to be +additive (but non-breaking), according to commonly observed practices. + +* `^1.2.3` := `>=1.2.3 <2.0.0-0` +* `^0.2.3` := `>=0.2.3 <0.3.0-0` +* `^0.0.3` := `>=0.0.3 <0.0.4-0` +* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in + the `1.2.3` version will be allowed, if they are greater than or + equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but + `1.2.4-beta.2` would not, because it is a prerelease of a + different `[major, minor, patch]` tuple. +* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the + `0.0.3` version *only* will be allowed, if they are greater than or + equal to `beta`. So, `0.0.3-pr.2` would be allowed. + +When parsing caret ranges, a missing `patch` value desugars to the +number `0`, but will allow flexibility within that value, even if the +major and minor versions are both `0`. + +* `^1.2.x` := `>=1.2.0 <2.0.0-0` +* `^0.0.x` := `>=0.0.0 <0.1.0-0` +* `^0.0` := `>=0.0.0 <0.1.0-0` + +A missing `minor` and `patch` values will desugar to zero, but also +allow flexibility within those values, even if the major version is +zero. + +* `^1.x` := `>=1.0.0 <2.0.0-0` +* `^0.x` := `>=0.0.0 <1.0.0-0` + +### Range Grammar + +Putting all this together, here is a Backus-Naur grammar for ranges, +for the benefit of parser authors: + +```bnf +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ +``` + +## Functions + +All methods and classes take a final `options` object argument. All +options in this object are `false` by default. The options supported +are: + +- `loose` Be more forgiving about not-quite-valid semver strings. + (Any resulting output will always be 100% strict compliant, of + course.) For backwards compatibility reasons, if the `options` + argument is a boolean value instead of an object, it is interpreted + to be the `loose` param. +- `includePrerelease` Set to suppress the [default + behavior](https://github.com/npm/node-semver#prerelease-tags) of + excluding prerelease tagged versions from ranges unless they are + explicitly opted into. + +Strict-mode Comparators and Ranges will be strict about the SemVer +strings that they parse. + +* `valid(v)`: Return the parsed version, or null if it's not valid. +* `inc(v, release)`: Return the version incremented by the release + type (`major`, `premajor`, `minor`, `preminor`, `patch`, + `prepatch`, or `prerelease`), or null if it's not valid + * `premajor` in one call will bump the version up to the next major + version and down to a prerelease of that major version. + `preminor`, and `prepatch` work the same way. + * If called from a non-prerelease version, the `prerelease` will work the + same as `prepatch`. It increments the patch version, then makes a + prerelease. If the input version is already a prerelease it simply + increments it. +* `prerelease(v)`: Returns an array of prerelease components, or null + if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` +* `major(v)`: Return the major version number. +* `minor(v)`: Return the minor version number. +* `patch(v)`: Return the patch version number. +* `intersects(r1, r2, loose)`: Return true if the two supplied ranges + or comparators intersect. +* `parse(v)`: Attempt to parse a string as a semantic version, returning either + a `SemVer` object or `null`. + +### Comparison + +* `gt(v1, v2)`: `v1 > v2` +* `gte(v1, v2)`: `v1 >= v2` +* `lt(v1, v2)`: `v1 < v2` +* `lte(v1, v2)`: `v1 <= v2` +* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent, + even if they're not the exact same string. You already know how to + compare strings. +* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. +* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call + the corresponding function above. `"==="` and `"!=="` do simple + string comparison, but are included for completeness. Throws if an + invalid comparison string is provided. +* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions + in descending order when passed to `Array.sort()`. +* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions + are equal. Sorts in ascending order if passed to `Array.sort()`. + `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. +* `diff(v1, v2)`: Returns difference between two versions by the release type + (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), + or null if the versions are the same. + +### Comparators + +* `intersects(comparator)`: Return true if the comparators intersect + +### Ranges + +* `validRange(range)`: Return the valid range or null if it's not valid +* `satisfies(version, range)`: Return true if the version satisfies the + range. +* `maxSatisfying(versions, range)`: Return the highest version in the list + that satisfies the range, or `null` if none of them do. +* `minSatisfying(versions, range)`: Return the lowest version in the list + that satisfies the range, or `null` if none of them do. +* `minVersion(range)`: Return the lowest version that can possibly match + the given range. +* `gtr(version, range)`: Return `true` if version is greater than all the + versions possible in the range. +* `ltr(version, range)`: Return `true` if version is less than all the + versions possible in the range. +* `outside(version, range, hilo)`: Return true if the version is outside + the bounds of the range in either the high or low direction. The + `hilo` argument must be either the string `'>'` or `'<'`. (This is + the function called by `gtr` and `ltr`.) +* `intersects(range)`: Return true if any of the ranges comparators intersect +* `simplifyRange(versions, range)`: Return a "simplified" range that + matches the same items in `versions` list as the range specified. Note + that it does *not* guarantee that it would match the same versions in all + cases, only for the set of versions provided. This is useful when + generating ranges by joining together multiple versions with `||` + programmatically, to provide the user with something a bit more + ergonomic. If the provided range is shorter in string-length than the + generated range, then that is returned. +* `subset(subRange, superRange)`: Return `true` if the `subRange` range is + entirely contained by the `superRange` range. + +Note that, since ranges may be non-contiguous, a version might not be +greater than a range, less than a range, *or* satisfy a range! For +example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` +until `2.0.0`, so the version `1.2.10` would not be greater than the +range (because `2.0.1` satisfies, which is higher), nor less than the +range (since `1.2.8` satisfies, which is lower), and it also does not +satisfy the range. + +If you want to know if a version satisfies or does not satisfy a +range, use the `satisfies(version, range)` function. + +### Coercion + +* `coerce(version, options)`: Coerces a string to semver if possible + +This aims to provide a very forgiving translation of a non-semver string to +semver. It looks for the first digit in a string, and consumes all +remaining characters which satisfy at least a partial semver (e.g., `1`, +`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer +versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All +surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes +`3.4.0`). Only text which lacks digits will fail coercion (`version one` +is not valid). The maximum length for any semver component considered for +coercion is 16 characters; longer components will be ignored +(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any +semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value +components are invalid (`9999999999999999.4.7.4` is likely invalid). + +If the `options.rtl` flag is set, then `coerce` will return the right-most +coercible tuple that does not share an ending index with a longer coercible +tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not +`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of +any other overlapping SemVer tuple. + +### Clean + +* `clean(version)`: Clean a string to be a valid semver if possible + +This will return a cleaned and trimmed semver version. If the provided +version is not valid a null will be returned. This does not work for +ranges. + +ex. +* `s.clean(' = v 2.1.5foo')`: `null` +* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean(' = v 2.1.5-foo')`: `null` +* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` +* `s.clean('=v2.1.5')`: `'2.1.5'` +* `s.clean(' =v2.1.5')`: `2.1.5` +* `s.clean(' 2.1.5 ')`: `'2.1.5'` +* `s.clean('~1.0.0')`: `null` + +## Exported Modules + + + +You may pull in just the part of this semver utility that you need, if you +are sensitive to packing and tree-shaking concerns. The main +`require('semver')` export uses getter functions to lazily load the parts +of the API that are used. + +The following modules are available: + +* `require('semver')` +* `require('semver/classes')` +* `require('semver/classes/comparator')` +* `require('semver/classes/range')` +* `require('semver/classes/semver')` +* `require('semver/functions/clean')` +* `require('semver/functions/cmp')` +* `require('semver/functions/coerce')` +* `require('semver/functions/compare')` +* `require('semver/functions/compare-build')` +* `require('semver/functions/compare-loose')` +* `require('semver/functions/diff')` +* `require('semver/functions/eq')` +* `require('semver/functions/gt')` +* `require('semver/functions/gte')` +* `require('semver/functions/inc')` +* `require('semver/functions/lt')` +* `require('semver/functions/lte')` +* `require('semver/functions/major')` +* `require('semver/functions/minor')` +* `require('semver/functions/neq')` +* `require('semver/functions/parse')` +* `require('semver/functions/patch')` +* `require('semver/functions/prerelease')` +* `require('semver/functions/rcompare')` +* `require('semver/functions/rsort')` +* `require('semver/functions/satisfies')` +* `require('semver/functions/sort')` +* `require('semver/functions/valid')` +* `require('semver/ranges/gtr')` +* `require('semver/ranges/intersects')` +* `require('semver/ranges/ltr')` +* `require('semver/ranges/max-satisfying')` +* `require('semver/ranges/min-satisfying')` +* `require('semver/ranges/min-version')` +* `require('semver/ranges/outside')` +* `require('semver/ranges/to-comparators')` +* `require('semver/ranges/valid')` diff --git a/node_modules/jest-snapshot/node_modules/semver/bin/semver.js b/node_modules/jest-snapshot/node_modules/semver/bin/semver.js new file mode 100644 index 0000000..8d1b557 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/bin/semver.js @@ -0,0 +1,183 @@ +#!/usr/bin/env node +// Standalone semver comparison program. +// Exits successfully and prints matching version(s) if +// any supplied version is valid and passes all tests. + +const argv = process.argv.slice(2) + +let versions = [] + +const range = [] + +let inc = null + +const version = require('../package.json').version + +let loose = false + +let includePrerelease = false + +let coerce = false + +let rtl = false + +let identifier + +const semver = require('../') + +let reverse = false + +let options = {} + +const main = () => { + if (!argv.length) { + return help() + } + while (argv.length) { + let a = argv.shift() + const indexOfEqualSign = a.indexOf('=') + if (indexOfEqualSign !== -1) { + const value = a.slice(indexOfEqualSign + 1) + a = a.slice(0, indexOfEqualSign) + argv.unshift(value) + } + switch (a) { + case '-rv': case '-rev': case '--rev': case '--reverse': + reverse = true + break + case '-l': case '--loose': + loose = true + break + case '-p': case '--include-prerelease': + includePrerelease = true + break + case '-v': case '--version': + versions.push(argv.shift()) + break + case '-i': case '--inc': case '--increment': + switch (argv[0]) { + case 'major': case 'minor': case 'patch': case 'prerelease': + case 'premajor': case 'preminor': case 'prepatch': + inc = argv.shift() + break + default: + inc = 'patch' + break + } + break + case '--preid': + identifier = argv.shift() + break + case '-r': case '--range': + range.push(argv.shift()) + break + case '-c': case '--coerce': + coerce = true + break + case '--rtl': + rtl = true + break + case '--ltr': + rtl = false + break + case '-h': case '--help': case '-?': + return help() + default: + versions.push(a) + break + } + } + + options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl } + + versions = versions.map((v) => { + return coerce ? (semver.coerce(v, options) || { version: v }).version : v + }).filter((v) => { + return semver.valid(v) + }) + if (!versions.length) { + return fail() + } + if (inc && (versions.length !== 1 || range.length)) { + return failInc() + } + + for (let i = 0, l = range.length; i < l; i++) { + versions = versions.filter((v) => { + return semver.satisfies(v, range[i], options) + }) + if (!versions.length) { + return fail() + } + } + return success(versions) +} + +const failInc = () => { + console.error('--inc can only be used on a single version with no range') + fail() +} + +const fail = () => process.exit(1) + +const success = () => { + const compare = reverse ? 'rcompare' : 'compare' + versions.sort((a, b) => { + return semver[compare](a, b, options) + }).map((v) => { + return semver.clean(v, options) + }).map((v) => { + return inc ? semver.inc(v, inc, options, identifier) : v + }).forEach((v, i, _) => { + console.log(v) + }) +} + +const help = () => console.log( +`SemVer ${version} + +A JavaScript implementation of the https://semver.org/ specification +Copyright Isaac Z. Schlueter + +Usage: semver [options] [ [...]] +Prints valid versions sorted by SemVer precedence + +Options: +-r --range + Print versions that match the specified range. + +-i --increment [] + Increment a version by the specified level. Level can + be one of: major, minor, patch, premajor, preminor, + prepatch, or prerelease. Default level is 'patch'. + Only one version may be specified. + +--preid + Identifier to be used to prefix premajor, preminor, + prepatch or prerelease version increments. + +-l --loose + Interpret versions and ranges loosely + +-p --include-prerelease + Always include prerelease versions in range matching + +-c --coerce + Coerce a string into SemVer if possible + (does not imply --loose) + +--rtl + Coerce version strings right to left + +--ltr + Coerce version strings left to right (default) + +Program exits successfully if any valid version satisfies +all supplied ranges, and prints all satisfying versions. + +If no satisfying versions are found, then exits failure. + +Versions are printed in ascending order, so supplying +multiple versions to the utility will just sort them.`) + +main() diff --git a/node_modules/jest-snapshot/node_modules/semver/classes/comparator.js b/node_modules/jest-snapshot/node_modules/semver/classes/comparator.js new file mode 100644 index 0000000..62cd204 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/classes/comparator.js @@ -0,0 +1,136 @@ +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false, + } + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + const sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + const sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + const sameSemVer = this.semver.version === comp.semver.version + const differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + const oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<') + const oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>') + + return ( + sameDirectionIncreasing || + sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || + oppositeDirectionsGreaterThan + ) + } +} + +module.exports = Comparator + +const parseOptions = require('../internal/parse-options') +const { re, t } = require('../internal/re') +const cmp = require('../functions/cmp') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const Range = require('./range') diff --git a/node_modules/jest-snapshot/node_modules/semver/classes/index.js b/node_modules/jest-snapshot/node_modules/semver/classes/index.js new file mode 100644 index 0000000..5e3f5c9 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/classes/index.js @@ -0,0 +1,5 @@ +module.exports = { + SemVer: require('./semver.js'), + Range: require('./range.js'), + Comparator: require('./comparator.js'), +} diff --git a/node_modules/jest-snapshot/node_modules/semver/classes/range.js b/node_modules/jest-snapshot/node_modules/semver/classes/range.js new file mode 100644 index 0000000..a791d91 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/classes/range.js @@ -0,0 +1,522 @@ +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.format() + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First, split based on boolean or || + this.raw = range + this.set = range + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${range}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } + + this.format() + } + + format () { + this.range = this.set + .map((comps) => { + return comps.join(' ').trim() + }) + .join('||') + .trim() + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + range = range.trim() + + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = Object.keys(this.options).join(',') + const memoKey = `parseRange:${memoOpts}:${range}` + const cached = cache.get(memoKey) + if (cached) { + return cached + } + + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + + // normalize spaces + range = range.split(/\s+/).join(' ') + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } + + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} +module.exports = Range + +const LRU = require('lru-cache') +const cache = new LRU({ max: 1000 }) + +const parseOptions = require('../internal/parse-options') +const Comparator = require('./comparator') +const debug = require('../internal/debug') +const SemVer = require('./semver') +const { + re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = require('../internal/re') + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => + comp.trim().split(/\s+/).map((c) => { + return replaceTilde(c, options) + }).join(' ') + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => + comp.trim().split(/\s+/).map((c) => { + return replaceCaret(c, options) + }).join(' ') + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map((c) => { + return replaceXRange(c, options) + }).join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') { + pr = '-0' + } + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp.trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } + + return (`${from} ${to}`).trim() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} diff --git a/node_modules/jest-snapshot/node_modules/semver/classes/semver.js b/node_modules/jest-snapshot/node_modules/semver/classes/semver.js new file mode 100644 index 0000000..af62955 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/classes/semver.js @@ -0,0 +1,287 @@ +const debug = require('../internal/debug') +const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants') +const { re, t } = require('../internal/re') + +const parseOptions = require('../internal/parse-options') +const { compareIdentifiers } = require('../internal/identifiers') +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return ( + compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) + ) + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break + + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.format() + this.raw = this.version + return this + } +} + +module.exports = SemVer diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/clean.js b/node_modules/jest-snapshot/node_modules/semver/functions/clean.js new file mode 100644 index 0000000..811fe6b --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/clean.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/cmp.js b/node_modules/jest-snapshot/node_modules/semver/functions/cmp.js new file mode 100644 index 0000000..4011909 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/cmp.js @@ -0,0 +1,52 @@ +const eq = require('./eq') +const neq = require('./neq') +const gt = require('./gt') +const gte = require('./gte') +const lt = require('./lt') +const lte = require('./lte') + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b + + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/coerce.js b/node_modules/jest-snapshot/node_modules/semver/functions/coerce.js new file mode 100644 index 0000000..2e01452 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/coerce.js @@ -0,0 +1,52 @@ +const SemVer = require('../classes/semver') +const parse = require('./parse') +const { re, t } = require('../internal/re') + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + let next + while ((next = re[t.COERCERTL].exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + re[t.COERCERTL].lastIndex = -1 + } + + if (match === null) { + return null + } + + return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options) +} +module.exports = coerce diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/compare-build.js b/node_modules/jest-snapshot/node_modules/semver/functions/compare-build.js new file mode 100644 index 0000000..9eb881b --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/compare-build.js @@ -0,0 +1,7 @@ +const SemVer = require('../classes/semver') +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/compare-loose.js b/node_modules/jest-snapshot/node_modules/semver/functions/compare-loose.js new file mode 100644 index 0000000..4881fbe --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/compare-loose.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/compare.js b/node_modules/jest-snapshot/node_modules/semver/functions/compare.js new file mode 100644 index 0000000..748b7af --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/compare.js @@ -0,0 +1,5 @@ +const SemVer = require('../classes/semver') +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/diff.js b/node_modules/jest-snapshot/node_modules/semver/functions/diff.js new file mode 100644 index 0000000..87200ef --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/diff.js @@ -0,0 +1,23 @@ +const parse = require('./parse') +const eq = require('./eq') + +const diff = (version1, version2) => { + if (eq(version1, version2)) { + return null + } else { + const v1 = parse(version1) + const v2 = parse(version2) + const hasPre = v1.prerelease.length || v2.prerelease.length + const prefix = hasPre ? 'pre' : '' + const defaultResult = hasPre ? 'prerelease' : '' + for (const key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } +} +module.exports = diff diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/eq.js b/node_modules/jest-snapshot/node_modules/semver/functions/eq.js new file mode 100644 index 0000000..271fed9 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/eq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/gt.js b/node_modules/jest-snapshot/node_modules/semver/functions/gt.js new file mode 100644 index 0000000..d9b2156 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/gt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/gte.js b/node_modules/jest-snapshot/node_modules/semver/functions/gte.js new file mode 100644 index 0000000..5aeaa63 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/gte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/inc.js b/node_modules/jest-snapshot/node_modules/semver/functions/inc.js new file mode 100644 index 0000000..62d1da2 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/inc.js @@ -0,0 +1,18 @@ +const SemVer = require('../classes/semver') + +const inc = (version, release, options, identifier) => { + if (typeof (options) === 'string') { + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier).version + } catch (er) { + return null + } +} +module.exports = inc diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/lt.js b/node_modules/jest-snapshot/node_modules/semver/functions/lt.js new file mode 100644 index 0000000..b440ab7 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/lt.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/lte.js b/node_modules/jest-snapshot/node_modules/semver/functions/lte.js new file mode 100644 index 0000000..6dcc956 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/lte.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/major.js b/node_modules/jest-snapshot/node_modules/semver/functions/major.js new file mode 100644 index 0000000..4283165 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/major.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/minor.js b/node_modules/jest-snapshot/node_modules/semver/functions/minor.js new file mode 100644 index 0000000..57b3455 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/minor.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/neq.js b/node_modules/jest-snapshot/node_modules/semver/functions/neq.js new file mode 100644 index 0000000..f944c01 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/neq.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/parse.js b/node_modules/jest-snapshot/node_modules/semver/functions/parse.js new file mode 100644 index 0000000..a66663a --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/parse.js @@ -0,0 +1,33 @@ +const { MAX_LENGTH } = require('../internal/constants') +const { re, t } = require('../internal/re') +const SemVer = require('../classes/semver') + +const parseOptions = require('../internal/parse-options') +const parse = (version, options) => { + options = parseOptions(options) + + if (version instanceof SemVer) { + return version + } + + if (typeof version !== 'string') { + return null + } + + if (version.length > MAX_LENGTH) { + return null + } + + const r = options.loose ? re[t.LOOSE] : re[t.FULL] + if (!r.test(version)) { + return null + } + + try { + return new SemVer(version, options) + } catch (er) { + return null + } +} + +module.exports = parse diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/patch.js b/node_modules/jest-snapshot/node_modules/semver/functions/patch.js new file mode 100644 index 0000000..63afca2 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/patch.js @@ -0,0 +1,3 @@ +const SemVer = require('../classes/semver') +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/prerelease.js b/node_modules/jest-snapshot/node_modules/semver/functions/prerelease.js new file mode 100644 index 0000000..06aa132 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/prerelease.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/rcompare.js b/node_modules/jest-snapshot/node_modules/semver/functions/rcompare.js new file mode 100644 index 0000000..0ac509e --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/rcompare.js @@ -0,0 +1,3 @@ +const compare = require('./compare') +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/rsort.js b/node_modules/jest-snapshot/node_modules/semver/functions/rsort.js new file mode 100644 index 0000000..82404c5 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/rsort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/satisfies.js b/node_modules/jest-snapshot/node_modules/semver/functions/satisfies.js new file mode 100644 index 0000000..50af1c1 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/satisfies.js @@ -0,0 +1,10 @@ +const Range = require('../classes/range') +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/sort.js b/node_modules/jest-snapshot/node_modules/semver/functions/sort.js new file mode 100644 index 0000000..4d10917 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/sort.js @@ -0,0 +1,3 @@ +const compareBuild = require('./compare-build') +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort diff --git a/node_modules/jest-snapshot/node_modules/semver/functions/valid.js b/node_modules/jest-snapshot/node_modules/semver/functions/valid.js new file mode 100644 index 0000000..f27bae1 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/functions/valid.js @@ -0,0 +1,6 @@ +const parse = require('./parse') +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid diff --git a/node_modules/jest-snapshot/node_modules/semver/index.js b/node_modules/jest-snapshot/node_modules/semver/index.js new file mode 100644 index 0000000..4a342c6 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/index.js @@ -0,0 +1,88 @@ +// just pre-load all the stuff that index.js lazily exports +const internalRe = require('./internal/re') +const constants = require('./internal/constants') +const SemVer = require('./classes/semver') +const identifiers = require('./internal/identifiers') +const parse = require('./functions/parse') +const valid = require('./functions/valid') +const clean = require('./functions/clean') +const inc = require('./functions/inc') +const diff = require('./functions/diff') +const major = require('./functions/major') +const minor = require('./functions/minor') +const patch = require('./functions/patch') +const prerelease = require('./functions/prerelease') +const compare = require('./functions/compare') +const rcompare = require('./functions/rcompare') +const compareLoose = require('./functions/compare-loose') +const compareBuild = require('./functions/compare-build') +const sort = require('./functions/sort') +const rsort = require('./functions/rsort') +const gt = require('./functions/gt') +const lt = require('./functions/lt') +const eq = require('./functions/eq') +const neq = require('./functions/neq') +const gte = require('./functions/gte') +const lte = require('./functions/lte') +const cmp = require('./functions/cmp') +const coerce = require('./functions/coerce') +const Comparator = require('./classes/comparator') +const Range = require('./classes/range') +const satisfies = require('./functions/satisfies') +const toComparators = require('./ranges/to-comparators') +const maxSatisfying = require('./ranges/max-satisfying') +const minSatisfying = require('./ranges/min-satisfying') +const minVersion = require('./ranges/min-version') +const validRange = require('./ranges/valid') +const outside = require('./ranges/outside') +const gtr = require('./ranges/gtr') +const ltr = require('./ranges/ltr') +const intersects = require('./ranges/intersects') +const simplifyRange = require('./ranges/simplify') +const subset = require('./ranges/subset') +module.exports = { + parse, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, +} diff --git a/node_modules/jest-snapshot/node_modules/semver/internal/constants.js b/node_modules/jest-snapshot/node_modules/semver/internal/constants.js new file mode 100644 index 0000000..4f0de59 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/internal/constants.js @@ -0,0 +1,17 @@ +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +module.exports = { + SEMVER_SPEC_VERSION, + MAX_LENGTH, + MAX_SAFE_INTEGER, + MAX_SAFE_COMPONENT_LENGTH, +} diff --git a/node_modules/jest-snapshot/node_modules/semver/internal/debug.js b/node_modules/jest-snapshot/node_modules/semver/internal/debug.js new file mode 100644 index 0000000..1c00e13 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/internal/debug.js @@ -0,0 +1,9 @@ +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug diff --git a/node_modules/jest-snapshot/node_modules/semver/internal/identifiers.js b/node_modules/jest-snapshot/node_modules/semver/internal/identifiers.js new file mode 100644 index 0000000..e612d0a --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/internal/identifiers.js @@ -0,0 +1,23 @@ +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers, +} diff --git a/node_modules/jest-snapshot/node_modules/semver/internal/parse-options.js b/node_modules/jest-snapshot/node_modules/semver/internal/parse-options.js new file mode 100644 index 0000000..bbd9ec7 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/internal/parse-options.js @@ -0,0 +1,11 @@ +// parse out just the options we care about so we always get a consistent +// obj with keys in a consistent order. +const opts = ['includePrerelease', 'loose', 'rtl'] +const parseOptions = options => + !options ? {} + : typeof options !== 'object' ? { loose: true } + : opts.filter(k => options[k]).reduce((o, k) => { + o[k] = true + return o + }, {}) +module.exports = parseOptions diff --git a/node_modules/jest-snapshot/node_modules/semver/internal/re.js b/node_modules/jest-snapshot/node_modules/semver/internal/re.js new file mode 100644 index 0000000..ed88398 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/internal/re.js @@ -0,0 +1,182 @@ +const { MAX_SAFE_COMPONENT_LENGTH } = require('./constants') +const debug = require('./debug') +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const src = exports.src = [] +const t = exports.t = {} +let R = 0 + +const createToken = (name, value, isGlobal) => { + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*') + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE] +}|${src[t.NONNUMERICIDENTIFIER]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+') + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCE', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') diff --git a/node_modules/jest-snapshot/node_modules/semver/package.json b/node_modules/jest-snapshot/node_modules/semver/package.json new file mode 100644 index 0000000..72d3f66 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/package.json @@ -0,0 +1,86 @@ +{ + "name": "semver", + "version": "7.3.8", + "description": "The semantic version parser used by npm.", + "main": "index.js", + "scripts": { + "test": "tap", + "snap": "tap", + "lint": "eslint \"**/*.js\"", + "postlint": "template-oss-check", + "lintfix": "npm run lint -- --fix", + "posttest": "npm run lint", + "template-oss-apply": "template-oss-apply --force" + }, + "devDependencies": { + "@npmcli/eslint-config": "^3.0.1", + "@npmcli/template-oss": "4.4.4", + "tap": "^16.0.0" + }, + "license": "ISC", + "repository": { + "type": "git", + "url": "https://github.com/npm/node-semver.git" + }, + "bin": { + "semver": "bin/semver.js" + }, + "files": [ + "bin/", + "lib/", + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "tap": { + "check-coverage": true, + "coverage-map": "map.js", + "nyc-arg": [ + "--exclude", + "tap-snapshots/**" + ] + }, + "engines": { + "node": ">=10" + }, + "dependencies": { + "lru-cache": "^6.0.0" + }, + "author": "GitHub Inc.", + "templateOSS": { + "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", + "version": "4.4.4", + "engines": ">=10", + "content": "./scripts", + "ciVersions": [ + "10.0.0", + "10.x", + "12.x", + "14.x", + "16.x", + "18.x" + ], + "distPaths": [ + "classes/", + "functions/", + "internal/", + "ranges/", + "index.js", + "preload.js", + "range.bnf" + ], + "allowPaths": [ + "/classes/", + "/functions/", + "/internal/", + "/ranges/", + "/index.js", + "/preload.js", + "/range.bnf" + ] + } +} diff --git a/node_modules/jest-snapshot/node_modules/semver/preload.js b/node_modules/jest-snapshot/node_modules/semver/preload.js new file mode 100644 index 0000000..947cd4f --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/preload.js @@ -0,0 +1,2 @@ +// XXX remove in v8 or beyond +module.exports = require('./index.js') diff --git a/node_modules/jest-snapshot/node_modules/semver/range.bnf b/node_modules/jest-snapshot/node_modules/semver/range.bnf new file mode 100644 index 0000000..d4c6ae0 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/range.bnf @@ -0,0 +1,16 @@ +range-set ::= range ( logical-or range ) * +logical-or ::= ( ' ' ) * '||' ( ' ' ) * +range ::= hyphen | simple ( ' ' simple ) * | '' +hyphen ::= partial ' - ' partial +simple ::= primitive | partial | tilde | caret +primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial +partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? +xr ::= 'x' | 'X' | '*' | nr +nr ::= '0' | [1-9] ( [0-9] ) * +tilde ::= '~' partial +caret ::= '^' partial +qualifier ::= ( '-' pre )? ( '+' build )? +pre ::= parts +build ::= parts +parts ::= part ( '.' part ) * +part ::= nr | [-0-9A-Za-z]+ diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/gtr.js b/node_modules/jest-snapshot/node_modules/semver/ranges/gtr.js new file mode 100644 index 0000000..db7e355 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/gtr.js @@ -0,0 +1,4 @@ +// Determine if version is greater than all the versions possible in the range. +const outside = require('./outside') +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/intersects.js b/node_modules/jest-snapshot/node_modules/semver/ranges/intersects.js new file mode 100644 index 0000000..3d1a6f3 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/intersects.js @@ -0,0 +1,7 @@ +const Range = require('../classes/range') +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} +module.exports = intersects diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/ltr.js b/node_modules/jest-snapshot/node_modules/semver/ranges/ltr.js new file mode 100644 index 0000000..528a885 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/ltr.js @@ -0,0 +1,4 @@ +const outside = require('./outside') +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/max-satisfying.js b/node_modules/jest-snapshot/node_modules/semver/ranges/max-satisfying.js new file mode 100644 index 0000000..6e3d993 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/max-satisfying.js @@ -0,0 +1,25 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/min-satisfying.js b/node_modules/jest-snapshot/node_modules/semver/ranges/min-satisfying.js new file mode 100644 index 0000000..9b60974 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/min-satisfying.js @@ -0,0 +1,24 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/min-version.js b/node_modules/jest-snapshot/node_modules/semver/ranges/min-version.js new file mode 100644 index 0000000..350e1f7 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/min-version.js @@ -0,0 +1,61 @@ +const SemVer = require('../classes/semver') +const Range = require('../classes/range') +const gt = require('../functions/gt') + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin + } + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} +module.exports = minVersion diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/outside.js b/node_modules/jest-snapshot/node_modules/semver/ranges/outside.js new file mode 100644 index 0000000..ae99b10 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/outside.js @@ -0,0 +1,80 @@ +const SemVer = require('../classes/semver') +const Comparator = require('../classes/comparator') +const { ANY } = Comparator +const Range = require('../classes/range') +const satisfies = require('../functions/satisfies') +const gt = require('../functions/gt') +const lt = require('../functions/lt') +const lte = require('../functions/lte') +const gte = require('../functions/gte') + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +module.exports = outside diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/simplify.js b/node_modules/jest-snapshot/node_modules/semver/ranges/simplify.js new file mode 100644 index 0000000..618d5b6 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/simplify.js @@ -0,0 +1,47 @@ +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } + + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) + } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/subset.js b/node_modules/jest-snapshot/node_modules/semver/ranges/subset.js new file mode 100644 index 0000000..e0dea43 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/subset.js @@ -0,0 +1,244 @@ +const Range = require('../classes/range.js') +const Comparator = require('../classes/comparator.js') +const { ANY } = Comparator +const satisfies = require('../functions/satisfies.js') +const compare = require('../functions/compare.js') + +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } + + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true +} + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = [new Comparator('>=0.0.0-0')] + } else { + sub = [new Comparator('>=0.0.0')] + } + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = [new Comparator('>=0.0.0')] + } + } + + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } + + if (eqSet.size > 1) { + return null + } + + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } + + if (lt && !satisfies(eq, String(lt), options)) { + return null + } + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } + + return true + } + + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } + + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } + + return true +} + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +} + +module.exports = subset diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/to-comparators.js b/node_modules/jest-snapshot/node_modules/semver/ranges/to-comparators.js new file mode 100644 index 0000000..6c8bc7e --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/to-comparators.js @@ -0,0 +1,8 @@ +const Range = require('../classes/range') + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators diff --git a/node_modules/jest-snapshot/node_modules/semver/ranges/valid.js b/node_modules/jest-snapshot/node_modules/semver/ranges/valid.js new file mode 100644 index 0000000..365f356 --- /dev/null +++ b/node_modules/jest-snapshot/node_modules/semver/ranges/valid.js @@ -0,0 +1,11 @@ +const Range = require('../classes/range') +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange diff --git a/node_modules/jest-snapshot/package.json b/node_modules/jest-snapshot/package.json new file mode 100644 index 0000000..7f12bf1 --- /dev/null +++ b/node_modules/jest-snapshot/package.json @@ -0,0 +1,65 @@ +{ + "name": "jest-snapshot", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-snapshot" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@babel/core": "^7.11.6", + "@babel/generator": "^7.7.2", + "@babel/plugin-syntax-jsx": "^7.7.2", + "@babel/plugin-syntax-typescript": "^7.7.2", + "@babel/traverse": "^7.7.2", + "@babel/types": "^7.3.3", + "@jest/expect-utils": "^29.2.2", + "@jest/transform": "^29.2.2", + "@jest/types": "^29.2.1", + "@types/babel__traverse": "^7.0.6", + "@types/prettier": "^2.1.5", + "babel-preset-current-node-syntax": "^1.0.0", + "chalk": "^4.0.0", + "expect": "^29.2.2", + "graceful-fs": "^4.2.9", + "jest-diff": "^29.2.1", + "jest-get-type": "^29.2.0", + "jest-haste-map": "^29.2.1", + "jest-matcher-utils": "^29.2.2", + "jest-message-util": "^29.2.1", + "jest-util": "^29.2.1", + "natural-compare": "^1.4.0", + "pretty-format": "^29.2.1", + "semver": "^7.3.5" + }, + "devDependencies": { + "@babel/preset-flow": "^7.7.2", + "@babel/preset-react": "^7.12.1", + "@jest/test-utils": "^29.2.1", + "@tsd/typescript": "~4.8.2", + "@types/graceful-fs": "^4.1.3", + "@types/natural-compare": "^1.4.0", + "@types/semver": "^7.1.0", + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "prettier": "^2.1.1", + "tsd-lite": "^0.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-util/LICENSE b/node_modules/jest-util/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-util/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-util/build/ErrorWithStack.js b/node_modules/jest-util/build/ErrorWithStack.js new file mode 100644 index 0000000..a7fdfc0 --- /dev/null +++ b/node_modules/jest-util/build/ErrorWithStack.js @@ -0,0 +1,28 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class ErrorWithStack extends Error { + constructor(message, callsite, stackLimit) { + // Ensure we have a large stack length so we get full details. + const originalStackLimit = Error.stackTraceLimit; + if (stackLimit) { + Error.stackTraceLimit = Math.max(stackLimit, originalStackLimit || 10); + } + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, callsite); + } + Error.stackTraceLimit = originalStackLimit; + } +} +exports.default = ErrorWithStack; diff --git a/node_modules/jest-util/build/clearLine.js b/node_modules/jest-util/build/clearLine.js new file mode 100644 index 0000000..fbaf2c7 --- /dev/null +++ b/node_modules/jest-util/build/clearLine.js @@ -0,0 +1,18 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = clearLine; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function clearLine(stream) { + if (stream.isTTY) { + stream.write('\x1b[999D\x1b[K'); + } +} diff --git a/node_modules/jest-util/build/convertDescriptorToString.js b/node_modules/jest-util/build/convertDescriptorToString.js new file mode 100644 index 0000000..2b6b486 --- /dev/null +++ b/node_modules/jest-util/build/convertDescriptorToString.js @@ -0,0 +1,30 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = convertDescriptorToString; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function convertDescriptorToString(descriptor) { + switch (typeof descriptor) { + case 'function': + if (descriptor.name) { + return descriptor.name; + } + break; + case 'number': + case 'undefined': + return `${descriptor}`; + case 'string': + return descriptor; + } + throw new Error( + `Invalid first argument, ${descriptor}. It must be a named class, named function, number, or string.` + ); +} diff --git a/node_modules/jest-util/build/createDirectory.js b/node_modules/jest-util/build/createDirectory.js new file mode 100644 index 0000000..4d5a0f1 --- /dev/null +++ b/node_modules/jest-util/build/createDirectory.js @@ -0,0 +1,71 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = createDirectory; +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function createDirectory(path) { + try { + fs().mkdirSync(path, { + recursive: true + }); + } catch (e) { + if (e.code !== 'EEXIST') { + throw e; + } + } +} diff --git a/node_modules/jest-util/build/createProcessObject.js b/node_modules/jest-util/build/createProcessObject.js new file mode 100644 index 0000000..a5ddcf3 --- /dev/null +++ b/node_modules/jest-util/build/createProcessObject.js @@ -0,0 +1,109 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = createProcessObject; +var _deepCyclicCopy = _interopRequireDefault(require('./deepCyclicCopy')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const BLACKLIST = new Set(['env', 'mainModule', '_events']); +const isWin32 = process.platform === 'win32'; +const proto = Object.getPrototypeOf(process.env); + +// The "process.env" object has a bunch of particularities: first, it does not +// directly extend from Object; second, it converts any assigned value to a +// string; and third, it is case-insensitive in Windows. We use a proxy here to +// mimic it (see https://nodejs.org/api/process.html#process_process_env). + +function createProcessEnv() { + const real = Object.create(proto); + const lookup = {}; + function deletePropertyWin32(_target, key) { + for (const name in real) { + if (Object.prototype.hasOwnProperty.call(real, name)) { + if (typeof key === 'string') { + if (name.toLowerCase() === key.toLowerCase()) { + delete real[name]; + delete lookup[name.toLowerCase()]; + } + } else { + if (key === name) { + delete real[name]; + delete lookup[name]; + } + } + } + } + return true; + } + function deleteProperty(_target, key) { + delete real[key]; + delete lookup[key]; + return true; + } + function getProperty(_target, key) { + return real[key]; + } + function getPropertyWin32(_target, key) { + if (typeof key === 'string') { + return lookup[key in proto ? key : key.toLowerCase()]; + } else { + return real[key]; + } + } + const proxy = new Proxy(real, { + deleteProperty: isWin32 ? deletePropertyWin32 : deleteProperty, + get: isWin32 ? getPropertyWin32 : getProperty, + set(_target, key, value) { + const strValue = `${value}`; + if (typeof key === 'string') { + lookup[key.toLowerCase()] = strValue; + } + real[key] = strValue; + return true; + } + }); + return Object.assign(proxy, process.env); +} +function createProcessObject() { + const process = require('process'); + const newProcess = (0, _deepCyclicCopy.default)(process, { + blacklist: BLACKLIST, + keepPrototype: true + }); + try { + // This fails on Node 12, but it's already set to 'process' + newProcess[Symbol.toStringTag] = 'process'; + } catch (e) { + // Make sure it's actually set instead of potentially ignoring errors + if (newProcess[Symbol.toStringTag] !== 'process') { + e.message = `Unable to set toStringTag on process. Please open up an issue at https://github.com/facebook/jest\n\n${e.message}`; + throw e; + } + } + + // Sequentially execute all constructors over the object. + let proto = process; + while ((proto = Object.getPrototypeOf(proto))) { + if (typeof proto.constructor === 'function') { + proto.constructor.call(newProcess); + } + } + newProcess.env = createProcessEnv(); + newProcess.send = () => true; + Object.defineProperty(newProcess, 'domain', { + get() { + return process.domain; + } + }); + return newProcess; +} diff --git a/node_modules/jest-util/build/deepCyclicCopy.js b/node_modules/jest-util/build/deepCyclicCopy.js new file mode 100644 index 0000000..e591582 --- /dev/null +++ b/node_modules/jest-util/build/deepCyclicCopy.js @@ -0,0 +1,76 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = deepCyclicCopy; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const EMPTY = new Set(); +function deepCyclicCopy( + value, + options = { + blacklist: EMPTY, + keepPrototype: false + }, + cycles = new WeakMap() +) { + if (typeof value !== 'object' || value === null || Buffer.isBuffer(value)) { + return value; + } else if (cycles.has(value)) { + return cycles.get(value); + } else if (Array.isArray(value)) { + return deepCyclicCopyArray(value, options, cycles); + } else { + return deepCyclicCopyObject(value, options, cycles); + } +} +function deepCyclicCopyObject(object, options, cycles) { + const newObject = options.keepPrototype + ? Object.create(Object.getPrototypeOf(object)) + : {}; + const descriptors = Object.getOwnPropertyDescriptors(object); + cycles.set(object, newObject); + Object.keys(descriptors).forEach(key => { + if (options.blacklist && options.blacklist.has(key)) { + delete descriptors[key]; + return; + } + const descriptor = descriptors[key]; + if (typeof descriptor.value !== 'undefined') { + descriptor.value = deepCyclicCopy( + descriptor.value, + { + blacklist: EMPTY, + keepPrototype: options.keepPrototype + }, + cycles + ); + } + descriptor.configurable = true; + }); + return Object.defineProperties(newObject, descriptors); +} +function deepCyclicCopyArray(array, options, cycles) { + const newArray = options.keepPrototype + ? new (Object.getPrototypeOf(array).constructor)(array.length) + : []; + const length = array.length; + cycles.set(array, newArray); + for (let i = 0; i < length; i++) { + newArray[i] = deepCyclicCopy( + array[i], + { + blacklist: EMPTY, + keepPrototype: options.keepPrototype + }, + cycles + ); + } + return newArray; +} diff --git a/node_modules/jest-util/build/formatTime.js b/node_modules/jest-util/build/formatTime.js new file mode 100644 index 0000000..46a1c66 --- /dev/null +++ b/node_modules/jest-util/build/formatTime.js @@ -0,0 +1,24 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = formatTime; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function formatTime(time, prefixPower = -3, padLeftLength = 0) { + const prefixes = ['n', 'μ', 'm', '']; + const prefixIndex = Math.max( + 0, + Math.min( + Math.trunc(prefixPower / 3) + prefixes.length - 1, + prefixes.length - 1 + ) + ); + return `${String(time).padStart(padLeftLength)} ${prefixes[prefixIndex]}s`; +} diff --git a/node_modules/jest-util/build/globsToMatcher.js b/node_modules/jest-util/build/globsToMatcher.js new file mode 100644 index 0000000..037c886 --- /dev/null +++ b/node_modules/jest-util/build/globsToMatcher.js @@ -0,0 +1,98 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = globsToMatcher; +function _picomatch() { + const data = _interopRequireDefault(require('picomatch')); + _picomatch = function () { + return data; + }; + return data; +} +var _replacePathSepForGlob = _interopRequireDefault( + require('./replacePathSepForGlob') +); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const globsToMatchersMap = new Map(); +const picomatchOptions = { + dot: true +}; + +/** + * Converts a list of globs into a function that matches a path against the + * globs. + * + * Every time picomatch is called, it will parse the glob strings and turn + * them into regexp instances. Instead of calling picomatch repeatedly with + * the same globs, we can use this function which will build the picomatch + * matchers ahead of time and then have an optimized path for determining + * whether an individual path matches. + * + * This function is intended to match the behavior of `micromatch()`. + * + * @example + * const isMatch = globsToMatcher(['*.js', '!*.test.js']); + * isMatch('pizza.js'); // true + * isMatch('pizza.test.js'); // false + */ +function globsToMatcher(globs) { + if (globs.length === 0) { + // Since there were no globs given, we can simply have a fast path here and + // return with a very simple function. + return () => false; + } + const matchers = globs.map(glob => { + if (!globsToMatchersMap.has(glob)) { + const isMatch = (0, _picomatch().default)(glob, picomatchOptions, true); + const matcher = { + isMatch, + // Matchers that are negated have different behavior than matchers that + // are not negated, so we need to store this information ahead of time. + negated: isMatch.state.negated || !!isMatch.state.negatedExtglob + }; + globsToMatchersMap.set(glob, matcher); + } + return globsToMatchersMap.get(glob); + }); + return path => { + const replacedPath = (0, _replacePathSepForGlob.default)(path); + let kept = undefined; + let negatives = 0; + for (let i = 0; i < matchers.length; i++) { + const {isMatch, negated} = matchers[i]; + if (negated) { + negatives++; + } + const matched = isMatch(replacedPath); + if (!matched && negated) { + // The path was not matched, and the matcher is a negated matcher, so we + // want to omit the path. This means that the negative matcher is + // filtering the path out. + kept = false; + } else if (matched && !negated) { + // The path was matched, and the matcher is not a negated matcher, so we + // want to keep the path. + kept = true; + } + } + + // If all of the globs were negative globs, then we want to include the path + // as long as it was not explicitly not kept. Otherwise only include + // the path if it was kept. This allows sets of globs that are all negated + // to allow some paths to be matched, while sets of globs that are mixed + // negated and non-negated to cause the negated matchers to only omit paths + // and not keep them. + return negatives === matchers.length ? kept !== false : !!kept; + }; +} diff --git a/node_modules/jest-util/build/index.d.ts b/node_modules/jest-util/build/index.d.ts new file mode 100644 index 0000000..e390845 --- /dev/null +++ b/node_modules/jest-util/build/index.d.ts @@ -0,0 +1,125 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import type {Config} from '@jest/types'; +import type {Global} from '@jest/types'; + +declare const ARROW = ' \u203A '; + +declare const CLEAR: string; + +export declare function clearLine(stream: NodeJS.WriteStream): void; + +export declare function convertDescriptorToString( + descriptor: Global.BlockNameLike | undefined, +): string; + +export declare function createDirectory(path: string): void; + +export declare function deepCyclicCopy( + value: T, + options?: DeepCyclicCopyOptions, + cycles?: WeakMap, +): T; + +declare type DeepCyclicCopyOptions = { + blacklist?: Set; + keepPrototype?: boolean; +}; + +export declare class ErrorWithStack extends Error { + constructor( + message: string | undefined, + callsite: (...args: Array) => unknown, + stackLimit?: number, + ); +} + +export declare function formatTime( + time: number, + prefixPower?: number, + padLeftLength?: number, +): string; + +/** + * Converts a list of globs into a function that matches a path against the + * globs. + * + * Every time picomatch is called, it will parse the glob strings and turn + * them into regexp instances. Instead of calling picomatch repeatedly with + * the same globs, we can use this function which will build the picomatch + * matchers ahead of time and then have an optimized path for determining + * whether an individual path matches. + * + * This function is intended to match the behavior of `micromatch()`. + * + * @example + * const isMatch = globsToMatcher(['*.js', '!*.test.js']); + * isMatch('pizza.js'); // true + * isMatch('pizza.test.js'); // false + */ +export declare function globsToMatcher(globs: Array): Matcher; + +declare const ICONS: { + failed: string; + pending: string; + success: string; + todo: string; +}; + +export declare function installCommonGlobals( + globalObject: typeof globalThis, + globals: Config.ConfigGlobals, +): typeof globalThis & Config.ConfigGlobals; + +export declare function interopRequireDefault(obj: any): any; + +export declare const isInteractive: boolean; + +export declare function isPromise( + candidate: unknown, +): candidate is PromiseLike; + +declare type Matcher = (str: string) => boolean; + +export declare function pluralize(word: string, count: number): string; + +declare namespace preRunMessage { + export {print_2 as print, remove}; +} +export {preRunMessage}; + +declare function print_2(stream: NodeJS.WriteStream): void; + +declare function remove(stream: NodeJS.WriteStream): void; + +export declare function replacePathSepForGlob(path: string): string; + +export declare function requireOrImportModule( + filePath: string, + applyInteropRequireDefault?: boolean, +): Promise; + +export declare function setGlobal( + globalToMutate: typeof globalThis | Global.Global, + key: string, + value: unknown, +): void; + +declare namespace specialChars { + export {ARROW, ICONS, CLEAR}; +} +export {specialChars}; + +export declare function testPathPatternToRegExp( + testPathPattern: Config.GlobalConfig['testPathPattern'], +): RegExp; + +export declare function tryRealpath(path: string): string; + +export {}; diff --git a/node_modules/jest-util/build/index.js b/node_modules/jest-util/build/index.js new file mode 100644 index 0000000..dd41509 --- /dev/null +++ b/node_modules/jest-util/build/index.js @@ -0,0 +1,185 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'ErrorWithStack', { + enumerable: true, + get: function () { + return _ErrorWithStack.default; + } +}); +Object.defineProperty(exports, 'clearLine', { + enumerable: true, + get: function () { + return _clearLine.default; + } +}); +Object.defineProperty(exports, 'convertDescriptorToString', { + enumerable: true, + get: function () { + return _convertDescriptorToString.default; + } +}); +Object.defineProperty(exports, 'createDirectory', { + enumerable: true, + get: function () { + return _createDirectory.default; + } +}); +Object.defineProperty(exports, 'deepCyclicCopy', { + enumerable: true, + get: function () { + return _deepCyclicCopy.default; + } +}); +Object.defineProperty(exports, 'formatTime', { + enumerable: true, + get: function () { + return _formatTime.default; + } +}); +Object.defineProperty(exports, 'globsToMatcher', { + enumerable: true, + get: function () { + return _globsToMatcher.default; + } +}); +Object.defineProperty(exports, 'installCommonGlobals', { + enumerable: true, + get: function () { + return _installCommonGlobals.default; + } +}); +Object.defineProperty(exports, 'interopRequireDefault', { + enumerable: true, + get: function () { + return _interopRequireDefault.default; + } +}); +Object.defineProperty(exports, 'isInteractive', { + enumerable: true, + get: function () { + return _isInteractive.default; + } +}); +Object.defineProperty(exports, 'isPromise', { + enumerable: true, + get: function () { + return _isPromise.default; + } +}); +Object.defineProperty(exports, 'pluralize', { + enumerable: true, + get: function () { + return _pluralize.default; + } +}); +exports.preRunMessage = void 0; +Object.defineProperty(exports, 'replacePathSepForGlob', { + enumerable: true, + get: function () { + return _replacePathSepForGlob.default; + } +}); +Object.defineProperty(exports, 'requireOrImportModule', { + enumerable: true, + get: function () { + return _requireOrImportModule.default; + } +}); +Object.defineProperty(exports, 'setGlobal', { + enumerable: true, + get: function () { + return _setGlobal.default; + } +}); +exports.specialChars = void 0; +Object.defineProperty(exports, 'testPathPatternToRegExp', { + enumerable: true, + get: function () { + return _testPathPatternToRegExp.default; + } +}); +Object.defineProperty(exports, 'tryRealpath', { + enumerable: true, + get: function () { + return _tryRealpath.default; + } +}); +var preRunMessage = _interopRequireWildcard(require('./preRunMessage')); +exports.preRunMessage = preRunMessage; +var specialChars = _interopRequireWildcard(require('./specialChars')); +exports.specialChars = specialChars; +var _clearLine = _interopRequireDefault2(require('./clearLine')); +var _createDirectory = _interopRequireDefault2(require('./createDirectory')); +var _ErrorWithStack = _interopRequireDefault2(require('./ErrorWithStack')); +var _installCommonGlobals = _interopRequireDefault2( + require('./installCommonGlobals') +); +var _interopRequireDefault = _interopRequireDefault2( + require('./interopRequireDefault') +); +var _isInteractive = _interopRequireDefault2(require('./isInteractive')); +var _isPromise = _interopRequireDefault2(require('./isPromise')); +var _setGlobal = _interopRequireDefault2(require('./setGlobal')); +var _deepCyclicCopy = _interopRequireDefault2(require('./deepCyclicCopy')); +var _convertDescriptorToString = _interopRequireDefault2( + require('./convertDescriptorToString') +); +var _replacePathSepForGlob = _interopRequireDefault2( + require('./replacePathSepForGlob') +); +var _testPathPatternToRegExp = _interopRequireDefault2( + require('./testPathPatternToRegExp') +); +var _globsToMatcher = _interopRequireDefault2(require('./globsToMatcher')); +var _pluralize = _interopRequireDefault2(require('./pluralize')); +var _formatTime = _interopRequireDefault2(require('./formatTime')); +var _tryRealpath = _interopRequireDefault2(require('./tryRealpath')); +var _requireOrImportModule = _interopRequireDefault2( + require('./requireOrImportModule') +); +function _interopRequireDefault2(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} diff --git a/node_modules/jest-util/build/installCommonGlobals.js b/node_modules/jest-util/build/installCommonGlobals.js new file mode 100644 index 0000000..53816e0 --- /dev/null +++ b/node_modules/jest-util/build/installCommonGlobals.js @@ -0,0 +1,115 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = installCommonGlobals; +function fs() { + const data = _interopRequireWildcard(require('graceful-fs')); + fs = function () { + return data; + }; + return data; +} +var _createProcessObject = _interopRequireDefault( + require('./createProcessObject') +); +var _deepCyclicCopy = _interopRequireDefault(require('./deepCyclicCopy')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== 'function') return null; + var cacheBabelInterop = new WeakMap(); + var cacheNodeInterop = new WeakMap(); + return (_getRequireWildcardCache = function (nodeInterop) { + return nodeInterop ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); +} +function _interopRequireWildcard(obj, nodeInterop) { + if (!nodeInterop && obj && obj.__esModule) { + return obj; + } + if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) { + return {default: obj}; + } + var cache = _getRequireWildcardCache(nodeInterop); + if (cache && cache.has(obj)) { + return cache.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = + Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor + ? Object.getOwnPropertyDescriptor(obj, key) + : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj.default = obj; + if (cache) { + cache.set(obj, newObj); + } + return newObj; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const DTRACE = Object.keys(globalThis).filter(key => key.startsWith('DTRACE')); +function installCommonGlobals(globalObject, globals) { + globalObject.process = (0, _createProcessObject.default)(); + const symbol = globalObject.Symbol; + // Keep a reference to some globals that Jest needs + Object.defineProperties(globalObject, { + [symbol.for('jest-native-promise')]: { + enumerable: false, + value: Promise, + writable: false + }, + [symbol.for('jest-native-now')]: { + enumerable: false, + value: globalObject.Date.now.bind(globalObject.Date), + writable: false + }, + [symbol.for('jest-native-read-file')]: { + enumerable: false, + value: fs().readFileSync.bind(fs()), + writable: false + }, + [symbol.for('jest-native-write-file')]: { + enumerable: false, + value: fs().writeFileSync.bind(fs()), + writable: false + }, + [symbol.for('jest-native-exists-file')]: { + enumerable: false, + value: fs().existsSync.bind(fs()), + writable: false + }, + 'jest-symbol-do-not-touch': { + enumerable: false, + value: symbol, + writable: false + } + }); + + // Forward some APIs. + DTRACE.forEach(dtrace => { + // @ts-expect-error: no index + globalObject[dtrace] = function (...args) { + // @ts-expect-error: no index + return globalThis[dtrace].apply(this, args); + }; + }); + return Object.assign(globalObject, (0, _deepCyclicCopy.default)(globals)); +} diff --git a/node_modules/jest-util/build/interopRequireDefault.js b/node_modules/jest-util/build/interopRequireDefault.js new file mode 100644 index 0000000..121b79d --- /dev/null +++ b/node_modules/jest-util/build/interopRequireDefault.js @@ -0,0 +1,22 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = interopRequireDefault; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// copied from https://github.com/babel/babel/blob/56044c7851d583d498f919e9546caddf8f80a72f/packages/babel-helpers/src/helpers.js#L558-L562 +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function interopRequireDefault(obj) { + return obj && obj.__esModule + ? obj + : { + default: obj + }; +} diff --git a/node_modules/jest-util/build/isInteractive.js b/node_modules/jest-util/build/isInteractive.js new file mode 100644 index 0000000..c2ff3c6 --- /dev/null +++ b/node_modules/jest-util/build/isInteractive.js @@ -0,0 +1,21 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _ciInfo() { + const data = require('ci-info'); + _ciInfo = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ var _default = + !!process.stdout.isTTY && process.env.TERM !== 'dumb' && !_ciInfo().isCI; +exports.default = _default; diff --git a/node_modules/jest-util/build/isPromise.js b/node_modules/jest-util/build/isPromise.js new file mode 100644 index 0000000..bee0d33 --- /dev/null +++ b/node_modules/jest-util/build/isPromise.js @@ -0,0 +1,20 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = isPromise; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function isPromise(candidate) { + return ( + candidate != null && + (typeof candidate === 'object' || typeof candidate === 'function') && + typeof candidate.then === 'function' + ); +} diff --git a/node_modules/jest-util/build/pluralize.js b/node_modules/jest-util/build/pluralize.js new file mode 100644 index 0000000..5f03ccc --- /dev/null +++ b/node_modules/jest-util/build/pluralize.js @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = pluralize; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function pluralize(word, count) { + return `${count} ${word}${count === 1 ? '' : 's'}`; +} diff --git a/node_modules/jest-util/build/preRunMessage.js b/node_modules/jest-util/build/preRunMessage.js new file mode 100644 index 0000000..d71e885 --- /dev/null +++ b/node_modules/jest-util/build/preRunMessage.js @@ -0,0 +1,38 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.print = print; +exports.remove = remove; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +var _clearLine = _interopRequireDefault(require('./clearLine')); +var _isInteractive = _interopRequireDefault(require('./isInteractive')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function print(stream) { + if (_isInteractive.default) { + stream.write( + _chalk().default.bold.dim('Determining test suites to run...') + ); + } +} +function remove(stream) { + if (_isInteractive.default) { + (0, _clearLine.default)(stream); + } +} diff --git a/node_modules/jest-util/build/replacePathSepForGlob.js b/node_modules/jest-util/build/replacePathSepForGlob.js new file mode 100644 index 0000000..b8d821e --- /dev/null +++ b/node_modules/jest-util/build/replacePathSepForGlob.js @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = replacePathSepForGlob; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function replacePathSepForGlob(path) { + return path.replace(/\\(?![{}()+?.^$])/g, '/'); +} diff --git a/node_modules/jest-util/build/requireOrImportModule.js b/node_modules/jest-util/build/requireOrImportModule.js new file mode 100644 index 0000000..e2c0967 --- /dev/null +++ b/node_modules/jest-util/build/requireOrImportModule.js @@ -0,0 +1,77 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = requireOrImportModule; +function _path() { + const data = require('path'); + _path = function () { + return data; + }; + return data; +} +function _url() { + const data = require('url'); + _url = function () { + return data; + }; + return data; +} +var _interopRequireDefault = _interopRequireDefault2( + require('./interopRequireDefault') +); +function _interopRequireDefault2(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +async function requireOrImportModule( + filePath, + applyInteropRequireDefault = true +) { + if (!(0, _path().isAbsolute)(filePath) && filePath[0] === '.') { + throw new Error( + `Jest: requireOrImportModule path must be absolute, was "${filePath}"` + ); + } + try { + const requiredModule = require(filePath); + if (!applyInteropRequireDefault) { + return requiredModule; + } + return (0, _interopRequireDefault.default)(requiredModule).default; + } catch (error) { + if (error.code === 'ERR_REQUIRE_ESM') { + try { + const moduleUrl = (0, _url().pathToFileURL)(filePath); + + // node `import()` supports URL, but TypeScript doesn't know that + const importedModule = await import(moduleUrl.href); + if (!applyInteropRequireDefault) { + return importedModule; + } + if (!importedModule.default) { + throw new Error( + `Jest: Failed to load ESM at ${filePath} - did you use a default export?` + ); + } + return importedModule.default; + } catch (innerError) { + if (innerError.message === 'Not supported') { + throw new Error( + `Jest: Your version of Node does not support dynamic import - please enable it or use a .cjs file extension for file ${filePath}` + ); + } + throw innerError; + } + } else { + throw error; + } + } +} diff --git a/node_modules/jest-util/build/setGlobal.js b/node_modules/jest-util/build/setGlobal.js new file mode 100644 index 0000000..c5c55ec --- /dev/null +++ b/node_modules/jest-util/build/setGlobal.js @@ -0,0 +1,17 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = setGlobal; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function setGlobal(globalToMutate, key, value) { + // @ts-expect-error: no index + globalToMutate[key] = value; +} diff --git a/node_modules/jest-util/build/specialChars.js b/node_modules/jest-util/build/specialChars.js new file mode 100644 index 0000000..fa52b37 --- /dev/null +++ b/node_modules/jest-util/build/specialChars.js @@ -0,0 +1,25 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.ICONS = exports.CLEAR = exports.ARROW = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const isWindows = process.platform === 'win32'; +const ARROW = ' \u203A '; +exports.ARROW = ARROW; +const ICONS = { + failed: isWindows ? '\u00D7' : '\u2715', + pending: '\u25CB', + success: isWindows ? '\u221A' : '\u2713', + todo: '\u270E' +}; +exports.ICONS = ICONS; +const CLEAR = isWindows ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H'; +exports.CLEAR = CLEAR; diff --git a/node_modules/jest-util/build/testPathPatternToRegExp.js b/node_modules/jest-util/build/testPathPatternToRegExp.js new file mode 100644 index 0000000..c384c8c --- /dev/null +++ b/node_modules/jest-util/build/testPathPatternToRegExp.js @@ -0,0 +1,19 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = testPathPatternToRegExp; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Because we serialize/deserialize globalConfig when we spawn workers, +// we can't pass regular expression. Using this shared function on both sides +// will ensure that we produce consistent regexp for testPathPattern. +function testPathPatternToRegExp(testPathPattern) { + return new RegExp(testPathPattern, 'i'); +} diff --git a/node_modules/jest-util/build/tryRealpath.js b/node_modules/jest-util/build/tryRealpath.js new file mode 100644 index 0000000..406f16a --- /dev/null +++ b/node_modules/jest-util/build/tryRealpath.js @@ -0,0 +1,30 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = tryRealpath; +function _gracefulFs() { + const data = require('graceful-fs'); + _gracefulFs = function () { + return data; + }; + return data; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function tryRealpath(path) { + try { + path = _gracefulFs().realpathSync.native(path); + } catch (error) { + if (error.code !== 'ENOENT' && error.code !== 'EISDIR') { + throw error; + } + } + return path; +} diff --git a/node_modules/jest-util/package.json b/node_modules/jest-util/package.json new file mode 100644 index 0000000..179fbf9 --- /dev/null +++ b/node_modules/jest-util/package.json @@ -0,0 +1,38 @@ +{ + "name": "jest-util", + "version": "29.2.1", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-util" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/types": "^29.2.1", + "@types/node": "*", + "chalk": "^4.0.0", + "ci-info": "^3.2.0", + "graceful-fs": "^4.2.9", + "picomatch": "^2.2.3" + }, + "devDependencies": { + "@types/graceful-fs": "^4.1.3", + "@types/picomatch": "^2.2.2" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "4551c0fdd4d25b7206824957c7bcc6baf61e63bf" +} diff --git a/node_modules/jest-validate/LICENSE b/node_modules/jest-validate/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-validate/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-validate/README.md b/node_modules/jest-validate/README.md new file mode 100644 index 0000000..2406bd5 --- /dev/null +++ b/node_modules/jest-validate/README.md @@ -0,0 +1,196 @@ +# jest-validate + +Generic configuration validation tool that helps you with warnings, errors and deprecation messages as well as showing users examples of correct configuration. + +```bash +npm install --save jest-validate +``` + +## Usage + +```js +import {validate} from 'jest-validate'; + +validate(config, validationOptions); // => {hasDeprecationWarnings: boolean, isValid: boolean} +``` + +Where `ValidationOptions` are: + +```ts +type ValidationOptions = { + comment?: string; + condition?: (option: unknown, validOption: unknown) => boolean; + deprecate?: ( + config: Record, + option: string, + deprecatedOptions: DeprecatedOptions, + options: ValidationOptions, + ) => boolean; + deprecatedConfig?: DeprecatedOptions; + error?: ( + option: string, + received: unknown, + defaultValue: unknown, + options: ValidationOptions, + path?: Array, + ) => void; + exampleConfig: Record; + recursive?: boolean; + recursiveBlacklist?: Array; + recursiveDenylist?: Array; + title?: Title; + unknown?: ( + config: Record, + exampleConfig: Record, + option: string, + options: ValidationOptions, + path?: Array, + ) => void; +}; + +type Title = { + deprecation?: string; + error?: string; + warning?: string; +}; +``` + +`exampleConfig` is the only option required. + +## API + +By default `jest-validate` will print generic warning and error messages. You can however customize this behavior by providing `options: ValidationOptions` object as a second argument: + +Almost anything can be overwritten to suite your needs. + +### Options + +- `recursiveDenylist` – optional array of string keyPaths that should be excluded from deep (recursive) validation. +- `comment` – optional string to be rendered below error/warning message. +- `condition` – an optional function with validation condition. +- `deprecate`, `error`, `unknown` – optional functions responsible for displaying warning and error messages. +- `deprecatedConfig` – optional object with deprecated config keys. +- `exampleConfig` – the only **required** option with configuration against which you'd like to test. +- `recursive` - optional boolean determining whether recursively compare `exampleConfig` to `config` (default: `true`). +- `title` – optional object of titles for errors and messages. + +You will find examples of `condition`, `deprecate`, `error`, `unknown`, and `deprecatedConfig` inside source of this repository, named respectively. + +## exampleConfig syntax + +`exampleConfig` should be an object with key/value pairs that contain an example of a valid value for each key. A configuration value is considered valid when: + +- it matches the JavaScript type of the example value, e.g. `string`, `number`, `array`, `boolean`, `function`, or `object` +- it is `null` or `undefined` +- it matches the Javascript type of any of arguments passed to `MultipleValidOptions(...)` + +The last condition is a special syntax that allows validating where more than one type is permissible; see example below. It's acceptable to have multiple values of the same type in the example, so you can also use this syntax to provide more than one example. When a validation failure occurs, the error message will show all other values in the array as examples. + +## Examples + +Minimal example: + +```js +validate(config, {exampleConfig}); +``` + +Example with slight modifications: + +```js +validate(config, { + comment: ' Documentation: http://custom-docs.com', + deprecatedConfig, + exampleConfig, + title: { + deprecation: 'Custom Deprecation', + // leaving 'error' and 'warning' as default + }, +}); +``` + +This will output: + +#### Warning: + +```bash +● Validation Warning: + + Unknown option transformx with value "/node_modules/babel-jest" was found. + This is either a typing error or a user mistake. Fixing it will remove this message. + + Documentation: http://custom-docs.com +``` + +#### Error: + +```bash +● Validation Error: + + Option transform must be of type: + object + but instead received: + string + + Example: + { + "transform": { + "\\.js$": "/preprocessor.js" + } + } + + Documentation: http://custom-docs.com +``` + +## Example validating multiple types + +```js +import {multipleValidOptions} from 'jest-validate'; + +validate(config, { + // `bar` will accept either a string or a number + bar: multipleValidOptions('string is ok', 2), +}); +``` + +#### Error: + +```bash +● Validation Error: + + Option foo must be of type: + string or number + but instead received: + array + + Example: + { + "bar": "string is ok" + } + + or + + { + "bar": 2 + } + + Documentation: http://custom-docs.com +``` + +#### Deprecation + +Based on `deprecatedConfig` object with proper deprecation messages. Note custom title: + +```bash +Custom Deprecation: + + Option scriptPreprocessor was replaced by transform, which support multiple preprocessors. + + Jest now treats your current configuration as: + { + "transform": {".*": "xxx"} + } + + Please update your configuration. + + Documentation: http://custom-docs.com +``` diff --git a/node_modules/jest-validate/build/condition.js b/node_modules/jest-validate/build/condition.js new file mode 100644 index 0000000..b672359 --- /dev/null +++ b/node_modules/jest-validate/build/condition.js @@ -0,0 +1,44 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.getValues = getValues; +exports.multipleValidOptions = multipleValidOptions; +exports.validationCondition = validationCondition; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const toString = Object.prototype.toString; +const MULTIPLE_VALID_OPTIONS_SYMBOL = Symbol('JEST_MULTIPLE_VALID_OPTIONS'); +function validationConditionSingle(option, validOption) { + return ( + option === null || + option === undefined || + (typeof option === 'function' && typeof validOption === 'function') || + toString.call(option) === toString.call(validOption) + ); +} +function getValues(validOption) { + if ( + Array.isArray(validOption) && + // @ts-expect-error: no index signature + validOption[MULTIPLE_VALID_OPTIONS_SYMBOL] + ) { + return validOption; + } + return [validOption]; +} +function validationCondition(option, validOption) { + return getValues(validOption).some(e => validationConditionSingle(option, e)); +} +function multipleValidOptions(...args) { + const options = [...args]; + // @ts-expect-error: no index signature + options[MULTIPLE_VALID_OPTIONS_SYMBOL] = true; + return options; +} diff --git a/node_modules/jest-validate/build/defaultConfig.js b/node_modules/jest-validate/build/defaultConfig.js new file mode 100644 index 0000000..e1b6f97 --- /dev/null +++ b/node_modules/jest-validate/build/defaultConfig.js @@ -0,0 +1,37 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _condition = require('./condition'); +var _deprecated = require('./deprecated'); +var _errors = require('./errors'); +var _utils = require('./utils'); +var _warnings = require('./warnings'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const validationOptions = { + comment: '', + condition: _condition.validationCondition, + deprecate: _deprecated.deprecationWarning, + deprecatedConfig: {}, + error: _errors.errorMessage, + exampleConfig: {}, + recursive: true, + // Allow NPM-sanctioned comments in package.json. Use a "//" key. + recursiveDenylist: ['//'], + title: { + deprecation: _utils.DEPRECATION, + error: _utils.ERROR, + warning: _utils.WARNING + }, + unknown: _warnings.unknownOptionWarning +}; +var _default = validationOptions; +exports.default = _default; diff --git a/node_modules/jest-validate/build/deprecated.js b/node_modules/jest-validate/build/deprecated.js new file mode 100644 index 0000000..dec3b34 --- /dev/null +++ b/node_modules/jest-validate/build/deprecated.js @@ -0,0 +1,28 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.deprecationWarning = void 0; +var _utils = require('./utils'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const deprecationMessage = (message, options) => { + const comment = options.comment; + const name = + (options.title && options.title.deprecation) || _utils.DEPRECATION; + (0, _utils.logValidationWarning)(name, message, comment); +}; +const deprecationWarning = (config, option, deprecatedOptions, options) => { + if (option in deprecatedOptions) { + deprecationMessage(deprecatedOptions[option](config), options); + return true; + } + return false; +}; +exports.deprecationWarning = deprecationWarning; diff --git a/node_modules/jest-validate/build/errors.js b/node_modules/jest-validate/build/errors.js new file mode 100644 index 0000000..b2b5c9f --- /dev/null +++ b/node_modules/jest-validate/build/errors.js @@ -0,0 +1,64 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.errorMessage = void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestGetType() { + const data = require('jest-get-type'); + _jestGetType = function () { + return data; + }; + return data; +} +var _condition = require('./condition'); +var _utils = require('./utils'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const errorMessage = (option, received, defaultValue, options, path) => { + const conditions = (0, _condition.getValues)(defaultValue); + const validTypes = Array.from( + new Set(conditions.map(_jestGetType().getType)) + ); + const message = ` Option ${_chalk().default.bold( + `"${path && path.length > 0 ? `${path.join('.')}.` : ''}${option}"` + )} must be of type: + ${validTypes.map(e => _chalk().default.bold.green(e)).join(' or ')} + but instead received: + ${_chalk().default.bold.red((0, _jestGetType().getType)(received))} + + Example: +${formatExamples(option, conditions)}`; + const comment = options.comment; + const name = (options.title && options.title.error) || _utils.ERROR; + throw new _utils.ValidationError(name, message, comment); +}; +exports.errorMessage = errorMessage; +function formatExamples(option, examples) { + return examples.map( + e => ` { + ${_chalk().default.bold(`"${option}"`)}: ${_chalk().default.bold( + (0, _utils.formatPrettyObject)(e) + )} + }` + ).join(` + + or + +`); +} diff --git a/node_modules/jest-validate/build/exampleConfig.js b/node_modules/jest-validate/build/exampleConfig.js new file mode 100644 index 0000000..500c8e0 --- /dev/null +++ b/node_modules/jest-validate/build/exampleConfig.js @@ -0,0 +1,38 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const config = { + comment: ' A comment', + condition: () => true, + deprecate: () => false, + deprecatedConfig: { + key: () => 'Deprecation message' + }, + // eslint-disable-next-line @typescript-eslint/no-empty-function + error: () => {}, + exampleConfig: { + key: 'value', + test: 'case' + }, + recursive: true, + recursiveDenylist: [], + title: { + deprecation: 'Deprecation Warning', + error: 'Validation Error', + warning: 'Validation Warning' + }, + // eslint-disable-next-line @typescript-eslint/no-empty-function + unknown: () => {} +}; +var _default = config; +exports.default = _default; diff --git a/node_modules/jest-validate/build/index.d.ts b/node_modules/jest-validate/build/index.d.ts new file mode 100644 index 0000000..ff3894e --- /dev/null +++ b/node_modules/jest-validate/build/index.d.ts @@ -0,0 +1,89 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config} from '@jest/types'; +import type {Options} from 'yargs'; + +export declare const createDidYouMeanMessage: ( + unrecognized: string, + allowedOptions: Array, +) => string; + +declare type DeprecatedOptionFunc = (arg: Record) => string; + +export declare type DeprecatedOptions = Record; + +export declare const format: (value: unknown) => string; + +export declare const logValidationWarning: ( + name: string, + message: string, + comment?: string | null, +) => void; + +export declare function multipleValidOptions>( + ...args: T +): T[number]; + +declare type Title = { + deprecation?: string; + error?: string; + warning?: string; +}; + +export declare const validate: ( + config: Record, + options: ValidationOptions, +) => { + hasDeprecationWarnings: boolean; + isValid: boolean; +}; + +export declare function validateCLIOptions( + argv: Config.Argv, + options?: Record & { + deprecationEntries?: DeprecatedOptions; + }, + rawArgv?: Array, +): boolean; + +export declare class ValidationError extends Error { + name: string; + message: string; + constructor(name: string, message: string, comment?: string | null); +} + +declare type ValidationOptions = { + comment?: string; + condition?: (option: unknown, validOption: unknown) => boolean; + deprecate?: ( + config: Record, + option: string, + deprecatedOptions: DeprecatedOptions, + options: ValidationOptions, + ) => boolean; + deprecatedConfig?: DeprecatedOptions; + error?: ( + option: string, + received: unknown, + defaultValue: unknown, + options: ValidationOptions, + path?: Array, + ) => void; + exampleConfig: Record; + recursive?: boolean; + recursiveDenylist?: Array; + title?: Title; + unknown?: ( + config: Record, + exampleConfig: Record, + option: string, + options: ValidationOptions, + path?: Array, + ) => void; +}; + +export {}; diff --git a/node_modules/jest-validate/build/index.js b/node_modules/jest-validate/build/index.js new file mode 100644 index 0000000..d0e6b1d --- /dev/null +++ b/node_modules/jest-validate/build/index.js @@ -0,0 +1,56 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'ValidationError', { + enumerable: true, + get: function () { + return _utils.ValidationError; + } +}); +Object.defineProperty(exports, 'createDidYouMeanMessage', { + enumerable: true, + get: function () { + return _utils.createDidYouMeanMessage; + } +}); +Object.defineProperty(exports, 'format', { + enumerable: true, + get: function () { + return _utils.format; + } +}); +Object.defineProperty(exports, 'logValidationWarning', { + enumerable: true, + get: function () { + return _utils.logValidationWarning; + } +}); +Object.defineProperty(exports, 'multipleValidOptions', { + enumerable: true, + get: function () { + return _condition.multipleValidOptions; + } +}); +Object.defineProperty(exports, 'validate', { + enumerable: true, + get: function () { + return _validate.default; + } +}); +Object.defineProperty(exports, 'validateCLIOptions', { + enumerable: true, + get: function () { + return _validateCLIOptions.default; + } +}); +var _utils = require('./utils'); +var _validate = _interopRequireDefault(require('./validate')); +var _validateCLIOptions = _interopRequireDefault( + require('./validateCLIOptions') +); +var _condition = require('./condition'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} diff --git a/node_modules/jest-validate/build/types.js b/node_modules/jest-validate/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-validate/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-validate/build/utils.js b/node_modules/jest-validate/build/utils.js new file mode 100644 index 0000000..9e043a2 --- /dev/null +++ b/node_modules/jest-validate/build/utils.js @@ -0,0 +1,98 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.logValidationWarning = + exports.formatPrettyObject = + exports.format = + exports.createDidYouMeanMessage = + exports.WARNING = + exports.ValidationError = + exports.ERROR = + exports.DEPRECATION = + void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _leven() { + const data = _interopRequireDefault(require('leven')); + _leven = function () { + return data; + }; + return data; +} +function _prettyFormat() { + const data = require('pretty-format'); + _prettyFormat = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const BULLET = _chalk().default.bold('\u25cf'); +const DEPRECATION = `${BULLET} Deprecation Warning`; +exports.DEPRECATION = DEPRECATION; +const ERROR = `${BULLET} Validation Error`; +exports.ERROR = ERROR; +const WARNING = `${BULLET} Validation Warning`; +exports.WARNING = WARNING; +const format = value => + typeof value === 'function' + ? value.toString() + : (0, _prettyFormat().format)(value, { + min: true + }); +exports.format = format; +const formatPrettyObject = value => + typeof value === 'function' + ? value.toString() + : JSON.stringify(value, null, 2).split('\n').join('\n '); +exports.formatPrettyObject = formatPrettyObject; +class ValidationError extends Error { + name; + message; + constructor(name, message, comment) { + super(); + comment = comment ? `\n\n${comment}` : '\n'; + this.name = ''; + this.message = _chalk().default.red( + `${_chalk().default.bold(name)}:\n\n${message}${comment}` + ); + // eslint-disable-next-line @typescript-eslint/no-empty-function + Error.captureStackTrace(this, () => {}); + } +} +exports.ValidationError = ValidationError; +const logValidationWarning = (name, message, comment) => { + comment = comment ? `\n\n${comment}` : '\n'; + console.warn( + _chalk().default.yellow( + `${_chalk().default.bold(name)}:\n\n${message}${comment}` + ) + ); +}; +exports.logValidationWarning = logValidationWarning; +const createDidYouMeanMessage = (unrecognized, allowedOptions) => { + const suggestion = allowedOptions.find(option => { + const steps = (0, _leven().default)(option, unrecognized); + return steps < 3; + }); + return suggestion + ? `Did you mean ${_chalk().default.bold(format(suggestion))}?` + : ''; +}; +exports.createDidYouMeanMessage = createDidYouMeanMessage; diff --git a/node_modules/jest-validate/build/validate.js b/node_modules/jest-validate/build/validate.js new file mode 100644 index 0000000..2cb4c05 --- /dev/null +++ b/node_modules/jest-validate/build/validate.js @@ -0,0 +1,117 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _defaultConfig = _interopRequireDefault(require('./defaultConfig')); +var _utils = require('./utils'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +let hasDeprecationWarnings = false; +const shouldSkipValidationForPath = (path, key, denylist) => + denylist ? denylist.includes([...path, key].join('.')) : false; +const _validate = (config, exampleConfig, options, path = []) => { + if ( + typeof config !== 'object' || + config == null || + typeof exampleConfig !== 'object' || + exampleConfig == null + ) { + return { + hasDeprecationWarnings + }; + } + for (const key in config) { + if ( + options.deprecatedConfig && + key in options.deprecatedConfig && + typeof options.deprecate === 'function' + ) { + const isDeprecatedKey = options.deprecate( + config, + key, + options.deprecatedConfig, + options + ); + hasDeprecationWarnings = hasDeprecationWarnings || isDeprecatedKey; + } else if (allowsMultipleTypes(key)) { + const value = config[key]; + if ( + typeof options.condition === 'function' && + typeof options.error === 'function' + ) { + if (key === 'maxWorkers' && !isOfTypeStringOrNumber(value)) { + throw new _utils.ValidationError( + 'Validation Error', + `${key} has to be of type string or number`, + 'maxWorkers=50% or\nmaxWorkers=3' + ); + } + } + } else if (Object.hasOwnProperty.call(exampleConfig, key)) { + if ( + typeof options.condition === 'function' && + typeof options.error === 'function' && + !options.condition(config[key], exampleConfig[key]) + ) { + options.error(key, config[key], exampleConfig[key], options, path); + } + } else if ( + shouldSkipValidationForPath(path, key, options.recursiveDenylist) + ) { + // skip validating unknown options inside blacklisted paths + } else { + options.unknown && + options.unknown(config, exampleConfig, key, options, path); + } + if ( + options.recursive && + !Array.isArray(exampleConfig[key]) && + options.recursiveDenylist && + !shouldSkipValidationForPath(path, key, options.recursiveDenylist) + ) { + _validate(config[key], exampleConfig[key], options, [...path, key]); + } + } + return { + hasDeprecationWarnings + }; +}; +const allowsMultipleTypes = key => key === 'maxWorkers'; +const isOfTypeStringOrNumber = value => + typeof value === 'number' || typeof value === 'string'; +const validate = (config, options) => { + hasDeprecationWarnings = false; + + // Preserve default denylist entries even with user-supplied denylist + const combinedDenylist = [ + ...(_defaultConfig.default.recursiveDenylist || []), + ...(options.recursiveDenylist || []) + ]; + const defaultedOptions = Object.assign({ + ..._defaultConfig.default, + ...options, + recursiveDenylist: combinedDenylist, + title: options.title || _defaultConfig.default.title + }); + const {hasDeprecationWarnings: hdw} = _validate( + config, + options.exampleConfig, + defaultedOptions + ); + return { + hasDeprecationWarnings: hdw, + isValid: true + }; +}; +var _default = validate; +exports.default = _default; diff --git a/node_modules/jest-validate/build/validateCLIOptions.js b/node_modules/jest-validate/build/validateCLIOptions.js new file mode 100644 index 0000000..570bd8d --- /dev/null +++ b/node_modules/jest-validate/build/validateCLIOptions.js @@ -0,0 +1,118 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.DOCUMENTATION_NOTE = void 0; +exports.default = validateCLIOptions; +function _camelcase() { + const data = _interopRequireDefault(require('camelcase')); + _camelcase = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +var _defaultConfig = _interopRequireDefault(require('./defaultConfig')); +var _deprecated = require('./deprecated'); +var _utils = require('./utils'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const BULLET = _chalk().default.bold('\u25cf'); +const DOCUMENTATION_NOTE = ` ${_chalk().default.bold( + 'CLI Options Documentation:' +)} + https://jestjs.io/docs/cli +`; +exports.DOCUMENTATION_NOTE = DOCUMENTATION_NOTE; +const createCLIValidationError = (unrecognizedOptions, allowedOptions) => { + let title = `${BULLET} Unrecognized CLI Parameter`; + let message; + const comment = + ` ${_chalk().default.bold('CLI Options Documentation')}:\n` + + ' https://jestjs.io/docs/cli\n'; + if (unrecognizedOptions.length === 1) { + const unrecognized = unrecognizedOptions[0]; + const didYouMeanMessage = + unrecognized.length > 1 + ? (0, _utils.createDidYouMeanMessage)( + unrecognized, + Array.from(allowedOptions) + ) + : ''; + message = ` Unrecognized option ${_chalk().default.bold( + (0, _utils.format)(unrecognized) + )}.${didYouMeanMessage ? ` ${didYouMeanMessage}` : ''}`; + } else { + title += 's'; + message = + ' Following options were not recognized:\n' + + ` ${_chalk().default.bold((0, _utils.format)(unrecognizedOptions))}`; + } + return new _utils.ValidationError(title, message, comment); +}; +const logDeprecatedOptions = (deprecatedOptions, deprecationEntries, argv) => { + deprecatedOptions.forEach(opt => { + (0, _deprecated.deprecationWarning)(argv, opt, deprecationEntries, { + ..._defaultConfig.default, + comment: DOCUMENTATION_NOTE + }); + }); +}; +function validateCLIOptions(argv, options = {}, rawArgv = []) { + const yargsSpecialOptions = ['$0', '_', 'help', 'h']; + const deprecationEntries = options.deprecationEntries ?? {}; + const allowedOptions = Object.keys(options).reduce( + (acc, option) => acc.add(option).add(options[option].alias || option), + new Set(yargsSpecialOptions) + ); + const unrecognizedOptions = Object.keys(argv).filter( + arg => + !allowedOptions.has( + (0, _camelcase().default)(arg, { + locale: 'en-US' + }) + ) && + !allowedOptions.has(arg) && + (!rawArgv.length || rawArgv.includes(arg)), + [] + ); + if (unrecognizedOptions.length) { + throw createCLIValidationError(unrecognizedOptions, allowedOptions); + } + const CLIDeprecations = Object.keys(deprecationEntries).reduce( + (acc, entry) => { + if (options[entry]) { + acc[entry] = deprecationEntries[entry]; + const alias = options[entry].alias; + if (alias) { + acc[alias] = deprecationEntries[entry]; + } + } + return acc; + }, + {} + ); + const deprecations = new Set(Object.keys(CLIDeprecations)); + const deprecatedOptions = Object.keys(argv).filter( + arg => deprecations.has(arg) && argv[arg] != null + ); + if (deprecatedOptions.length) { + logDeprecatedOptions(deprecatedOptions, CLIDeprecations, argv); + } + return true; +} diff --git a/node_modules/jest-validate/build/warnings.js b/node_modules/jest-validate/build/warnings.js new file mode 100644 index 0000000..1a377a3 --- /dev/null +++ b/node_modules/jest-validate/build/warnings.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.unknownOptionWarning = void 0; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +var _utils = require('./utils'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const unknownOptionWarning = (config, exampleConfig, option, options, path) => { + const didYouMean = (0, _utils.createDidYouMeanMessage)( + option, + Object.keys(exampleConfig) + ); + const message = ` Unknown option ${_chalk().default.bold( + `"${path && path.length > 0 ? `${path.join('.')}.` : ''}${option}"` + )} with value ${_chalk().default.bold( + (0, _utils.format)(config[option]) + )} was found.${ + didYouMean && ` ${didYouMean}` + }\n This is probably a typing mistake. Fixing it will remove this message.`; + const comment = options.comment; + const name = (options.title && options.title.warning) || _utils.WARNING; + (0, _utils.logValidationWarning)(name, message, comment); +}; +exports.unknownOptionWarning = unknownOptionWarning; diff --git a/node_modules/jest-validate/node_modules/camelcase/index.d.ts b/node_modules/jest-validate/node_modules/camelcase/index.d.ts new file mode 100644 index 0000000..9db94e5 --- /dev/null +++ b/node_modules/jest-validate/node_modules/camelcase/index.d.ts @@ -0,0 +1,103 @@ +declare namespace camelcase { + interface Options { + /** + Uppercase the first character: `foo-bar` → `FooBar`. + + @default false + */ + readonly pascalCase?: boolean; + + /** + Preserve the consecutive uppercase characters: `foo-BAR` → `FooBAR`. + + @default false + */ + readonly preserveConsecutiveUppercase?: boolean; + + /** + The locale parameter indicates the locale to be used to convert to upper/lower case according to any locale-specific case mappings. If multiple locales are given in an array, the best available locale is used. + + Setting `locale: false` ignores the platform locale and uses the [Unicode Default Case Conversion](https://unicode-org.github.io/icu/userguide/transforms/casemappings.html#simple-single-character-case-mapping) algorithm. + + Default: The host environment’s current locale. + + @example + ``` + import camelCase = require('camelcase'); + + camelCase('lorem-ipsum', {locale: 'en-US'}); + //=> 'loremIpsum' + camelCase('lorem-ipsum', {locale: 'tr-TR'}); + //=> 'loremİpsum' + camelCase('lorem-ipsum', {locale: ['en-US', 'en-GB']}); + //=> 'loremIpsum' + camelCase('lorem-ipsum', {locale: ['tr', 'TR', 'tr-TR']}); + //=> 'loremİpsum' + ``` + */ + readonly locale?: false | string | readonly string[]; + } +} + +/** +Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`. + +Correctly handles Unicode strings. + +@param input - String to convert to camel case. + +@example +``` +import camelCase = require('camelcase'); + +camelCase('foo-bar'); +//=> 'fooBar' + +camelCase('foo_bar'); +//=> 'fooBar' + +camelCase('Foo-Bar'); +//=> 'fooBar' + +camelCase('розовый_пушистый_единорог'); +//=> 'розовыйПушистыйЕдинорог' + +camelCase('Foo-Bar', {pascalCase: true}); +//=> 'FooBar' + +camelCase('--foo.bar', {pascalCase: false}); +//=> 'fooBar' + +camelCase('Foo-BAR', {preserveConsecutiveUppercase: true}); +//=> 'fooBAR' + +camelCase('fooBAR', {pascalCase: true, preserveConsecutiveUppercase: true})); +//=> 'FooBAR' + +camelCase('foo bar'); +//=> 'fooBar' + +console.log(process.argv[3]); +//=> '--foo-bar' +camelCase(process.argv[3]); +//=> 'fooBar' + +camelCase(['foo', 'bar']); +//=> 'fooBar' + +camelCase(['__foo__', '--bar'], {pascalCase: true}); +//=> 'FooBar' + +camelCase(['foo', 'BAR'], {pascalCase: true, preserveConsecutiveUppercase: true}) +//=> 'FooBAR' + +camelCase('lorem-ipsum', {locale: 'en-US'}); +//=> 'loremIpsum' +``` +*/ +declare function camelcase( + input: string | readonly string[], + options?: camelcase.Options +): string; + +export = camelcase; diff --git a/node_modules/jest-validate/node_modules/camelcase/index.js b/node_modules/jest-validate/node_modules/camelcase/index.js new file mode 100644 index 0000000..6ff4ee8 --- /dev/null +++ b/node_modules/jest-validate/node_modules/camelcase/index.js @@ -0,0 +1,113 @@ +'use strict'; + +const UPPERCASE = /[\p{Lu}]/u; +const LOWERCASE = /[\p{Ll}]/u; +const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; +const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; +const SEPARATORS = /[_.\- ]+/; + +const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source); +const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu'); +const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu'); + +const preserveCamelCase = (string, toLowerCase, toUpperCase) => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + + for (let i = 0; i < string.length; i++) { + const character = string[i]; + + if (isLastCharLower && UPPERCASE.test(character)) { + string = string.slice(0, i) + '-' + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { + string = string.slice(0, i - 1) + '-' + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; + } + } + + return string; +}; + +const preserveConsecutiveUppercase = (input, toLowerCase) => { + LEADING_CAPITAL.lastIndex = 0; + + return input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1)); +}; + +const postProcess = (input, toUpperCase) => { + SEPARATORS_AND_IDENTIFIER.lastIndex = 0; + NUMBERS_AND_IDENTIFIER.lastIndex = 0; + + return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)) + .replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m)); +}; + +const camelCase = (input, options) => { + if (!(typeof input === 'string' || Array.isArray(input))) { + throw new TypeError('Expected the input to be `string | string[]`'); + } + + options = { + pascalCase: false, + preserveConsecutiveUppercase: false, + ...options + }; + + if (Array.isArray(input)) { + input = input.map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + input = input.trim(); + } + + if (input.length === 0) { + return ''; + } + + const toLowerCase = options.locale === false ? + string => string.toLowerCase() : + string => string.toLocaleLowerCase(options.locale); + const toUpperCase = options.locale === false ? + string => string.toUpperCase() : + string => string.toLocaleUpperCase(options.locale); + + if (input.length === 1) { + return options.pascalCase ? toUpperCase(input) : toLowerCase(input); + } + + const hasUpperCase = input !== toLowerCase(input); + + if (hasUpperCase) { + input = preserveCamelCase(input, toLowerCase, toUpperCase); + } + + input = input.replace(LEADING_SEPARATORS, ''); + + if (options.preserveConsecutiveUppercase) { + input = preserveConsecutiveUppercase(input, toLowerCase); + } else { + input = toLowerCase(input); + } + + if (options.pascalCase) { + input = toUpperCase(input.charAt(0)) + input.slice(1); + } + + return postProcess(input, toUpperCase); +}; + +module.exports = camelCase; +// TODO: Remove this for the next major release +module.exports.default = camelCase; diff --git a/node_modules/jest-validate/node_modules/camelcase/license b/node_modules/jest-validate/node_modules/camelcase/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/jest-validate/node_modules/camelcase/license @@ -0,0 +1,9 @@ +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. diff --git a/node_modules/jest-validate/node_modules/camelcase/package.json b/node_modules/jest-validate/node_modules/camelcase/package.json new file mode 100644 index 0000000..c433579 --- /dev/null +++ b/node_modules/jest-validate/node_modules/camelcase/package.json @@ -0,0 +1,44 @@ +{ + "name": "camelcase", + "version": "6.3.0", + "description": "Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`", + "license": "MIT", + "repository": "sindresorhus/camelcase", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "camelcase", + "camel-case", + "camel", + "case", + "dash", + "hyphen", + "dot", + "underscore", + "separator", + "string", + "text", + "convert", + "pascalcase", + "pascal-case" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.11.0", + "xo": "^0.28.3" + } +} diff --git a/node_modules/jest-validate/node_modules/camelcase/readme.md b/node_modules/jest-validate/node_modules/camelcase/readme.md new file mode 100644 index 0000000..0ff8f9e --- /dev/null +++ b/node_modules/jest-validate/node_modules/camelcase/readme.md @@ -0,0 +1,144 @@ +# camelcase + +> Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar` + +Correctly handles Unicode strings. + +If you use this on untrusted user input, don't forget to limit the length to something reasonable. + +## Install + +``` +$ npm install camelcase +``` + +*If you need to support Firefox < 78, stay on version 5 as version 6 uses regex features not available in Firefox < 78.* + +## Usage + +```js +const camelCase = require('camelcase'); + +camelCase('foo-bar'); +//=> 'fooBar' + +camelCase('foo_bar'); +//=> 'fooBar' + +camelCase('Foo-Bar'); +//=> 'fooBar' + +camelCase('розовый_пушистый_единорог'); +//=> 'розовыйПушистыйЕдинорог' + +camelCase('Foo-Bar', {pascalCase: true}); +//=> 'FooBar' + +camelCase('--foo.bar', {pascalCase: false}); +//=> 'fooBar' + +camelCase('Foo-BAR', {preserveConsecutiveUppercase: true}); +//=> 'fooBAR' + +camelCase('fooBAR', {pascalCase: true, preserveConsecutiveUppercase: true})); +//=> 'FooBAR' + +camelCase('foo bar'); +//=> 'fooBar' + +console.log(process.argv[3]); +//=> '--foo-bar' +camelCase(process.argv[3]); +//=> 'fooBar' + +camelCase(['foo', 'bar']); +//=> 'fooBar' + +camelCase(['__foo__', '--bar'], {pascalCase: true}); +//=> 'FooBar' + +camelCase(['foo', 'BAR'], {pascalCase: true, preserveConsecutiveUppercase: true}) +//=> 'FooBAR' + +camelCase('lorem-ipsum', {locale: 'en-US'}); +//=> 'loremIpsum' +``` + +## API + +### camelCase(input, options?) + +#### input + +Type: `string | string[]` + +String to convert to camel case. + +#### options + +Type: `object` + +##### pascalCase + +Type: `boolean`\ +Default: `false` + +Uppercase the first character: `foo-bar` → `FooBar` + +##### preserveConsecutiveUppercase + +Type: `boolean`\ +Default: `false` + +Preserve the consecutive uppercase characters: `foo-BAR` → `FooBAR`. + +##### locale + +Type: `false | string | string[]`\ +Default: The host environment’s current locale. + +The locale parameter indicates the locale to be used to convert to upper/lower case according to any locale-specific case mappings. If multiple locales are given in an array, the best available locale is used. + +```js +const camelCase = require('camelcase'); + +camelCase('lorem-ipsum', {locale: 'en-US'}); +//=> 'loremIpsum' + +camelCase('lorem-ipsum', {locale: 'tr-TR'}); +//=> 'loremİpsum' + +camelCase('lorem-ipsum', {locale: ['en-US', 'en-GB']}); +//=> 'loremIpsum' + +camelCase('lorem-ipsum', {locale: ['tr', 'TR', 'tr-TR']}); +//=> 'loremİpsum' +``` + +Setting `locale: false` ignores the platform locale and uses the [Unicode Default Case Conversion](https://unicode-org.github.io/icu/userguide/transforms/casemappings.html#simple-single-character-case-mapping) algorithm: + +```js +const camelCase = require('camelcase'); + +// On a platform with 'tr-TR' + +camelCase('lorem-ipsum'); +//=> 'loremİpsum' + +camelCase('lorem-ipsum', {locale: false}); +//=> 'loremIpsum' +``` + +## camelcase for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of camelcase and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-camelcase?utm_source=npm-camelcase&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +## Related + +- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module +- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase +- [titleize](https://github.com/sindresorhus/titleize) - Capitalize every word in string +- [humanize-string](https://github.com/sindresorhus/humanize-string) - Convert a camelized/dasherized/underscored string into a humanized one +- [camelcase-keys](https://github.com/sindresorhus/camelcase-keys) - Convert object keys to camel case diff --git a/node_modules/jest-validate/package.json b/node_modules/jest-validate/package.json new file mode 100644 index 0000000..80cb9e7 --- /dev/null +++ b/node_modules/jest-validate/package.json @@ -0,0 +1,37 @@ +{ + "name": "jest-validate", + "version": "29.2.2", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-validate" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/types": "^29.2.1", + "camelcase": "^6.2.0", + "chalk": "^4.0.0", + "jest-get-type": "^29.2.0", + "leven": "^3.1.0", + "pretty-format": "^29.2.1" + }, + "devDependencies": { + "@types/yargs": "^17.0.8" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-watcher/LICENSE b/node_modules/jest-watcher/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-watcher/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-watcher/build/BaseWatchPlugin.js b/node_modules/jest-watcher/build/BaseWatchPlugin.js new file mode 100644 index 0000000..ed9f455 --- /dev/null +++ b/node_modules/jest-watcher/build/BaseWatchPlugin.js @@ -0,0 +1,35 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class BaseWatchPlugin { + _stdin; + _stdout; + constructor({stdin, stdout}) { + this._stdin = stdin; + this._stdout = stdout; + } + + // eslint-disable-next-line @typescript-eslint/no-empty-function + apply(_hooks) {} + getUsageInfo(_globalConfig) { + return null; + } + + // eslint-disable-next-line @typescript-eslint/no-empty-function + onKey(_key) {} + run(_globalConfig, _updateConfigAndRun) { + return Promise.resolve(); + } +} +var _default = BaseWatchPlugin; +exports.default = _default; diff --git a/node_modules/jest-watcher/build/JestHooks.js b/node_modules/jest-watcher/build/JestHooks.js new file mode 100644 index 0000000..50d4d8e --- /dev/null +++ b/node_modules/jest-watcher/build/JestHooks.js @@ -0,0 +1,63 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class JestHooks { + _listeners; + _subscriber; + _emitter; + constructor() { + this._listeners = { + onFileChange: [], + onTestRunComplete: [], + shouldRunTestSuite: [] + }; + this._subscriber = { + onFileChange: fn => { + this._listeners.onFileChange.push(fn); + }, + onTestRunComplete: fn => { + this._listeners.onTestRunComplete.push(fn); + }, + shouldRunTestSuite: fn => { + this._listeners.shouldRunTestSuite.push(fn); + } + }; + this._emitter = { + onFileChange: fs => + this._listeners.onFileChange.forEach(listener => listener(fs)), + onTestRunComplete: results => + this._listeners.onTestRunComplete.forEach(listener => + listener(results) + ), + shouldRunTestSuite: async testSuiteInfo => { + const result = await Promise.all( + this._listeners.shouldRunTestSuite.map(listener => + listener(testSuiteInfo) + ) + ); + return result.every(Boolean); + } + }; + } + isUsed(hook) { + return this._listeners[hook]?.length > 0; + } + getSubscriber() { + return this._subscriber; + } + getEmitter() { + return this._emitter; + } +} +var _default = JestHooks; +exports.default = _default; diff --git a/node_modules/jest-watcher/build/PatternPrompt.js b/node_modules/jest-watcher/build/PatternPrompt.js new file mode 100644 index 0000000..792f969 --- /dev/null +++ b/node_modules/jest-watcher/build/PatternPrompt.js @@ -0,0 +1,74 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _ansiEscapes() { + const data = _interopRequireDefault(require('ansi-escapes')); + _ansiEscapes = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const {CLEAR} = _jestUtil().specialChars; +const usage = entity => + `\n${_chalk().default.bold('Pattern Mode Usage')}\n` + + ` ${_chalk().default.dim('\u203A Press')} Esc ${_chalk().default.dim( + 'to exit pattern mode.' + )}\n` + + ` ${_chalk().default.dim('\u203A Press')} Enter ` + + `${_chalk().default.dim(`to filter by a ${entity} regex pattern.`)}\n` + + '\n'; +const usageRows = usage('').split('\n').length; +class PatternPrompt { + _currentUsageRows; + constructor(_pipe, _prompt, _entityName = '') { + this._pipe = _pipe; + this._prompt = _prompt; + this._entityName = _entityName; + this._currentUsageRows = usageRows; + } + run(onSuccess, onCancel, options) { + this._pipe.write(_ansiEscapes().default.cursorHide); + this._pipe.write(CLEAR); + if (options && options.header) { + this._pipe.write(`${options.header}\n`); + this._currentUsageRows = usageRows + options.header.split('\n').length; + } else { + this._currentUsageRows = usageRows; + } + this._pipe.write(usage(this._entityName)); + this._pipe.write(_ansiEscapes().default.cursorShow); + this._prompt.enter(this._onChange.bind(this), onSuccess, onCancel); + } + _onChange(_pattern, _options) { + this._pipe.write(_ansiEscapes().default.eraseLine); + this._pipe.write(_ansiEscapes().default.cursorLeft); + } +} +exports.default = PatternPrompt; diff --git a/node_modules/jest-watcher/build/TestWatcher.js b/node_modules/jest-watcher/build/TestWatcher.js new file mode 100644 index 0000000..465ddc7 --- /dev/null +++ b/node_modules/jest-watcher/build/TestWatcher.js @@ -0,0 +1,45 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _emittery() { + const data = _interopRequireDefault(require('emittery')); + _emittery = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class TestWatcher extends _emittery().default { + state; + _isWatchMode; + constructor({isWatchMode}) { + super(); + this.state = { + interrupted: false + }; + this._isWatchMode = isWatchMode; + } + async setState(state) { + Object.assign(this.state, state); + await this.emit('change', this.state); + } + isInterrupted() { + return this.state.interrupted; + } + isWatchMode() { + return this._isWatchMode; + } +} +exports.default = TestWatcher; diff --git a/node_modules/jest-watcher/build/constants.js b/node_modules/jest-watcher/build/constants.js new file mode 100644 index 0000000..39edec7 --- /dev/null +++ b/node_modules/jest-watcher/build/constants.js @@ -0,0 +1,27 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.KEYS = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const isWindows = process.platform === 'win32'; +const KEYS = { + ARROW_DOWN: '\u001b[B', + ARROW_LEFT: '\u001b[D', + ARROW_RIGHT: '\u001b[C', + ARROW_UP: '\u001b[A', + BACKSPACE: Buffer.from(isWindows ? '08' : '7f', 'hex').toString(), + CONTROL_C: '\u0003', + CONTROL_D: '\u0004', + CONTROL_U: '\u0015', + ENTER: '\r', + ESCAPE: '\u001b' +}; +exports.KEYS = KEYS; diff --git a/node_modules/jest-watcher/build/index.d.ts b/node_modules/jest-watcher/build/index.d.ts new file mode 100644 index 0000000..ac0c9f5 --- /dev/null +++ b/node_modules/jest-watcher/build/index.d.ts @@ -0,0 +1,222 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import type {AggregatedResult} from '@jest/test-result'; +import type {Config} from '@jest/types'; +import Emittery = require('emittery'); + +export declare type AllowedConfigOptions = Partial< + Pick< + Config.GlobalConfig, + | 'bail' + | 'changedSince' + | 'collectCoverage' + | 'collectCoverageFrom' + | 'coverageDirectory' + | 'coverageReporters' + | 'findRelatedTests' + | 'nonFlagArgs' + | 'notify' + | 'notifyMode' + | 'onlyFailures' + | 'reporters' + | 'testNamePattern' + | 'testPathPattern' + | 'updateSnapshot' + | 'verbose' + > & { + mode: 'watch' | 'watchAll'; + } +>; + +declare type AvailableHooks = + | 'onFileChange' + | 'onTestRunComplete' + | 'shouldRunTestSuite'; + +export declare abstract class BaseWatchPlugin implements WatchPlugin { + protected _stdin: NodeJS.ReadStream; + protected _stdout: NodeJS.WriteStream; + constructor({ + stdin, + stdout, + }: { + stdin: NodeJS.ReadStream; + stdout: NodeJS.WriteStream; + }); + apply(_hooks: JestHookSubscriber): void; + getUsageInfo(_globalConfig: Config.GlobalConfig): UsageData | null; + onKey(_key: string): void; + run( + _globalConfig: Config.GlobalConfig, + _updateConfigAndRun: UpdateConfigCallback, + ): Promise; +} + +declare type FileChange = (fs: JestHookExposedFS) => void; + +export declare class JestHook { + private readonly _listeners; + private readonly _subscriber; + private readonly _emitter; + constructor(); + isUsed(hook: AvailableHooks): boolean; + getSubscriber(): Readonly; + getEmitter(): Readonly; +} + +export declare type JestHookEmitter = { + onFileChange: (fs: JestHookExposedFS) => void; + onTestRunComplete: (results: AggregatedResult) => void; + shouldRunTestSuite: ( + testSuiteInfo: TestSuiteInfo, + ) => Promise | boolean; +}; + +declare type JestHookExposedFS = { + projects: Array<{ + config: Config.ProjectConfig; + testPaths: Array; + }>; +}; + +export declare type JestHookSubscriber = { + onFileChange: (fn: FileChange) => void; + onTestRunComplete: (fn: TestRunComplete) => void; + shouldRunTestSuite: (fn: ShouldRunTestSuite) => void; +}; + +export declare const KEYS: { + ARROW_DOWN: string; + ARROW_LEFT: string; + ARROW_RIGHT: string; + ARROW_UP: string; + BACKSPACE: string; + CONTROL_C: string; + CONTROL_D: string; + CONTROL_U: string; + ENTER: string; + ESCAPE: string; +}; + +export declare abstract class PatternPrompt { + protected _pipe: NodeJS.WritableStream; + protected _prompt: Prompt; + protected _entityName: string; + protected _currentUsageRows: number; + constructor( + _pipe: NodeJS.WritableStream, + _prompt: Prompt, + _entityName?: string, + ); + run( + onSuccess: (value: string) => void, + onCancel: () => void, + options?: { + header: string; + }, + ): void; + protected _onChange(_pattern: string, _options: ScrollOptions_2): void; +} + +export declare function printPatternCaret( + pattern: string, + pipe: NodeJS.WritableStream, +): void; + +export declare function printRestoredPatternCaret( + pattern: string, + currentUsageRows: number, + pipe: NodeJS.WritableStream, +): void; + +export declare class Prompt { + private _entering; + private _value; + private _onChange; + private _onSuccess; + private _onCancel; + private _offset; + private _promptLength; + private _selection; + constructor(); + private readonly _onResize; + enter( + onChange: (pattern: string, options: ScrollOptions_2) => void, + onSuccess: (pattern: string) => void, + onCancel: () => void, + ): void; + setPromptLength(length: number): void; + setPromptSelection(selected: string): void; + put(key: string): void; + abort(): void; + isEntering(): boolean; +} + +declare type ScrollOptions_2 = { + offset: number; + max: number; +}; +export {ScrollOptions_2 as ScrollOptions}; + +declare type ShouldRunTestSuite = ( + testSuiteInfo: TestSuiteInfo, +) => Promise; + +declare type State = { + interrupted: boolean; +}; + +declare type TestRunComplete = (results: AggregatedResult) => void; + +declare type TestSuiteInfo = { + config: Config.ProjectConfig; + duration?: number; + testPath: string; +}; + +export declare class TestWatcher extends Emittery<{ + change: State; +}> { + state: State; + private readonly _isWatchMode; + constructor({isWatchMode}: {isWatchMode: boolean}); + setState(state: State): Promise; + isInterrupted(): boolean; + isWatchMode(): boolean; +} + +export declare type UpdateConfigCallback = ( + config?: AllowedConfigOptions, +) => void; + +export declare type UsageData = { + key: string; + prompt: string; +}; + +export declare interface WatchPlugin { + isInternal?: boolean; + apply?: (hooks: JestHookSubscriber) => void; + getUsageInfo?: (globalConfig: Config.GlobalConfig) => UsageData | null; + onKey?: (value: string) => void; + run?: ( + globalConfig: Config.GlobalConfig, + updateConfigAndRun: UpdateConfigCallback, + ) => Promise; +} + +export declare interface WatchPluginClass { + new (options: { + config: Record; + stdin: NodeJS.ReadStream; + stdout: NodeJS.WriteStream; + }): WatchPlugin; +} + +export {}; diff --git a/node_modules/jest-watcher/build/index.js b/node_modules/jest-watcher/build/index.js new file mode 100644 index 0000000..a1015f4 --- /dev/null +++ b/node_modules/jest-watcher/build/index.js @@ -0,0 +1,74 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +var _exportNames = { + BaseWatchPlugin: true, + JestHook: true, + PatternPrompt: true, + TestWatcher: true, + Prompt: true +}; +Object.defineProperty(exports, 'BaseWatchPlugin', { + enumerable: true, + get: function () { + return _BaseWatchPlugin.default; + } +}); +Object.defineProperty(exports, 'JestHook', { + enumerable: true, + get: function () { + return _JestHooks.default; + } +}); +Object.defineProperty(exports, 'PatternPrompt', { + enumerable: true, + get: function () { + return _PatternPrompt.default; + } +}); +Object.defineProperty(exports, 'Prompt', { + enumerable: true, + get: function () { + return _Prompt.default; + } +}); +Object.defineProperty(exports, 'TestWatcher', { + enumerable: true, + get: function () { + return _TestWatcher.default; + } +}); +var _BaseWatchPlugin = _interopRequireDefault(require('./BaseWatchPlugin')); +var _JestHooks = _interopRequireDefault(require('./JestHooks')); +var _PatternPrompt = _interopRequireDefault(require('./PatternPrompt')); +var _TestWatcher = _interopRequireDefault(require('./TestWatcher')); +var _constants = require('./constants'); +Object.keys(_constants).forEach(function (key) { + if (key === 'default' || key === '__esModule') return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _constants[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _constants[key]; + } + }); +}); +var _Prompt = _interopRequireDefault(require('./lib/Prompt')); +var _patternModeHelpers = require('./lib/patternModeHelpers'); +Object.keys(_patternModeHelpers).forEach(function (key) { + if (key === 'default' || key === '__esModule') return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _patternModeHelpers[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function () { + return _patternModeHelpers[key]; + } + }); +}); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} diff --git a/node_modules/jest-watcher/build/lib/Prompt.js b/node_modules/jest-watcher/build/lib/Prompt.js new file mode 100644 index 0000000..62a3f8e --- /dev/null +++ b/node_modules/jest-watcher/build/lib/Prompt.js @@ -0,0 +1,113 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _constants = require('../constants'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class Prompt { + _entering; + _value; + _onChange; + _onSuccess; + _onCancel; + _offset; + _promptLength; + _selection; + constructor() { + // Copied from `enter` to satisfy TS + this._entering = true; + this._value = ''; + this._selection = null; + this._offset = -1; + this._promptLength = 0; + + /* eslint-disable @typescript-eslint/no-empty-function */ + this._onChange = () => {}; + this._onSuccess = () => {}; + this._onCancel = () => {}; + /* eslint-enable */ + } + + _onResize = () => { + this._onChange(); + }; + enter(onChange, onSuccess, onCancel) { + this._entering = true; + this._value = ''; + this._onSuccess = onSuccess; + this._onCancel = onCancel; + this._selection = null; + this._offset = -1; + this._promptLength = 0; + this._onChange = () => + onChange(this._value, { + max: 10, + offset: this._offset + }); + this._onChange(); + process.stdout.on('resize', this._onResize); + } + setPromptLength(length) { + this._promptLength = length; + } + setPromptSelection(selected) { + this._selection = selected; + } + put(key) { + switch (key) { + case _constants.KEYS.ENTER: + this._entering = false; + this._onSuccess(this._selection ?? this._value); + this.abort(); + break; + case _constants.KEYS.ESCAPE: + this._entering = false; + this._onCancel(this._value); + this.abort(); + break; + case _constants.KEYS.ARROW_DOWN: + this._offset = Math.min(this._offset + 1, this._promptLength - 1); + this._onChange(); + break; + case _constants.KEYS.ARROW_UP: + this._offset = Math.max(this._offset - 1, -1); + this._onChange(); + break; + case _constants.KEYS.ARROW_LEFT: + case _constants.KEYS.ARROW_RIGHT: + break; + case _constants.KEYS.CONTROL_U: + this._value = ''; + this._offset = -1; + this._selection = null; + this._onChange(); + break; + default: + this._value = + key === _constants.KEYS.BACKSPACE + ? this._value.slice(0, -1) + : this._value + key; + this._offset = -1; + this._selection = null; + this._onChange(); + break; + } + } + abort() { + this._entering = false; + this._value = ''; + process.stdout.removeListener('resize', this._onResize); + } + isEntering() { + return this._entering; + } +} +exports.default = Prompt; diff --git a/node_modules/jest-watcher/build/lib/colorize.js b/node_modules/jest-watcher/build/lib/colorize.js new file mode 100644 index 0000000..7e52b24 --- /dev/null +++ b/node_modules/jest-watcher/build/lib/colorize.js @@ -0,0 +1,30 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = colorize; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function colorize(str, start, end) { + return ( + _chalk().default.dim(str.slice(0, start)) + + _chalk().default.reset(str.slice(start, end)) + + _chalk().default.dim(str.slice(end)) + ); +} diff --git a/node_modules/jest-watcher/build/lib/formatTestNameByPattern.js b/node_modules/jest-watcher/build/lib/formatTestNameByPattern.js new file mode 100644 index 0000000..977a52c --- /dev/null +++ b/node_modules/jest-watcher/build/lib/formatTestNameByPattern.js @@ -0,0 +1,67 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = formatTestNameByPattern; +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +var _colorize = _interopRequireDefault(require('./colorize')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const DOTS = '...'; +const ENTER = '⏎'; +function formatTestNameByPattern(testName, pattern, width) { + const inlineTestName = testName.replace(/(\r\n|\n|\r)/gm, ENTER); + let regexp; + try { + regexp = new RegExp(pattern, 'i'); + } catch { + return _chalk().default.dim(inlineTestName); + } + const match = inlineTestName.match(regexp); + if (!match) { + return _chalk().default.dim(inlineTestName); + } + const startPatternIndex = Math.max(match.index ?? 0, 0); + const endPatternIndex = startPatternIndex + match[0].length; + if (inlineTestName.length <= width) { + return (0, _colorize.default)( + inlineTestName, + startPatternIndex, + endPatternIndex + ); + } + const slicedTestName = inlineTestName.slice(0, width - DOTS.length); + if (startPatternIndex < slicedTestName.length) { + if (endPatternIndex > slicedTestName.length) { + return (0, _colorize.default)( + slicedTestName + DOTS, + startPatternIndex, + slicedTestName.length + DOTS.length + ); + } else { + return (0, _colorize.default)( + slicedTestName + DOTS, + Math.min(startPatternIndex, slicedTestName.length), + endPatternIndex + ); + } + } + return `${_chalk().default.dim(slicedTestName)}${_chalk().default.reset( + DOTS + )}`; +} diff --git a/node_modules/jest-watcher/build/lib/patternModeHelpers.js b/node_modules/jest-watcher/build/lib/patternModeHelpers.js new file mode 100644 index 0000000..9fcfc17 --- /dev/null +++ b/node_modules/jest-watcher/build/lib/patternModeHelpers.js @@ -0,0 +1,54 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.printPatternCaret = printPatternCaret; +exports.printRestoredPatternCaret = printRestoredPatternCaret; +function _ansiEscapes() { + const data = _interopRequireDefault(require('ansi-escapes')); + _ansiEscapes = function () { + return data; + }; + return data; +} +function _chalk() { + const data = _interopRequireDefault(require('chalk')); + _chalk = function () { + return data; + }; + return data; +} +function _stringLength() { + const data = _interopRequireDefault(require('string-length')); + _stringLength = function () { + return data; + }; + return data; +} +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function printPatternCaret(pattern, pipe) { + const inputText = `${_chalk().default.dim(' pattern \u203A')} ${pattern}`; + pipe.write(_ansiEscapes().default.eraseDown); + pipe.write(inputText); + pipe.write(_ansiEscapes().default.cursorSavePosition); +} +function printRestoredPatternCaret(pattern, currentUsageRows, pipe) { + const inputText = `${_chalk().default.dim(' pattern \u203A')} ${pattern}`; + pipe.write( + _ansiEscapes().default.cursorTo( + (0, _stringLength().default)(inputText), + currentUsageRows - 1 + ) + ); + pipe.write(_ansiEscapes().default.cursorRestorePosition); +} diff --git a/node_modules/jest-watcher/build/lib/scroll.js b/node_modules/jest-watcher/build/lib/scroll.js new file mode 100644 index 0000000..9375bb3 --- /dev/null +++ b/node_modules/jest-watcher/build/lib/scroll.js @@ -0,0 +1,31 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = scroll; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function scroll(size, {offset, max}) { + let start = 0; + let index = Math.min(offset, size); + const halfScreen = max / 2; + if (index <= halfScreen) { + start = 0; + } else { + if (size >= max) { + start = Math.min(index - halfScreen - 1, size - max); + } + index = Math.min(index - start, size); + } + return { + end: Math.min(size, start + max), + index, + start + }; +} diff --git a/node_modules/jest-watcher/build/types.js b/node_modules/jest-watcher/build/types.js new file mode 100644 index 0000000..ad9a93a --- /dev/null +++ b/node_modules/jest-watcher/build/types.js @@ -0,0 +1 @@ +'use strict'; diff --git a/node_modules/jest-watcher/package.json b/node_modules/jest-watcher/package.json new file mode 100644 index 0000000..1f9f14c --- /dev/null +++ b/node_modules/jest-watcher/package.json @@ -0,0 +1,41 @@ +{ + "name": "jest-watcher", + "description": "Delightful JavaScript Testing.", + "version": "29.2.2", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@jest/test-result": "^29.2.1", + "@jest/types": "^29.2.1", + "@types/node": "*", + "ansi-escapes": "^4.2.1", + "chalk": "^4.0.0", + "emittery": "^0.13.1", + "jest-util": "^29.2.1", + "string-length": "^4.0.1" + }, + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-watcher" + }, + "bugs": { + "url": "https://github.com/facebook/jest/issues" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "homepage": "https://jestjs.io/", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/jest-worker/LICENSE b/node_modules/jest-worker/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest-worker/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest-worker/README.md b/node_modules/jest-worker/README.md new file mode 100644 index 0000000..1277ed8 --- /dev/null +++ b/node_modules/jest-worker/README.md @@ -0,0 +1,266 @@ +# jest-worker + +Module for executing heavy tasks under forked processes in parallel, by providing a `Promise` based interface, minimum overhead, and bound workers. + +The module works by providing an absolute path of the module to be loaded in all forked processes. All methods are exposed on the parent process as promises, so they can be `await`'ed. Child (worker) methods can either be synchronous or asynchronous. + +The module also implements support for bound workers. Binding a worker means that, based on certain parameters, the same task will always be executed by the same worker. The way bound workers work is by using the returned string of the `computeWorkerKey` method. If the string was used before for a task, the call will be queued to the related worker that processed the task earlier; if not, it will be executed by the first available worker, then sticked to the worker that executed it; so the next time it will be processed by the same worker. If you have no preference on the worker executing the task, but you have defined a `computeWorkerKey` method because you want _some_ of the tasks to be sticked, you can return `null` from it. + +The list of exposed methods can be explicitly provided via the `exposedMethods` option. If it is not provided, it will be obtained by requiring the child module into the main process, and analyzed via reflection. Check the "minimal example" section for a valid one. + +## Install + +```sh +yarn add jest-worker +``` + +## Example + +This example covers the minimal usage: + +### File `parent.js` + +```js +import {Worker as JestWorker} from 'jest-worker'; + +async function main() { + const worker = new JestWorker(require.resolve('./worker')); + const result = await worker.hello('Alice'); // "Hello, Alice" +} + +main(); +``` + +### File `worker.js` + +```js +export function hello(param) { + return `Hello, ${param}`; +} +``` + +## Experimental worker + +Node shipped with [`worker_threads`](https://nodejs.org/api/worker_threads.html), a "threading API" that uses `SharedArrayBuffers` to communicate between the main process and its child threads. This feature can significantly improve the communication time between parent and child processes in `jest-worker`. + +To use `worker_threads` instead of default `child_process` you have to pass `enableWorkerThreads: true` when instantiating the worker. + +## API + +The `Worker` export is a constructor that is initialized by passing the worker path, plus an options object. + +### `workerPath: string` (required) + +Node module name or absolute path of the file to be loaded in the child processes. Use `require.resolve` to transform a relative path into an absolute one. + +### `options: Object` (optional) + +#### `computeWorkerKey: (method: string, ...args: Array) => string | null` (optional) + +Every time a method exposed via the API is called, `computeWorkerKey` is also called in order to bound the call to a worker. This is useful for workers that are able to cache the result or part of it. You bound calls to a worker by making `computeWorkerKey` return the same identifier for all different calls. If you do not want to bind the call to any worker, return `null`. + +The callback you provide is called with the method name, plus all the rest of the arguments of the call. Thus, you have full control to decide what to return. Check a practical example on bound workers under the "bound worker usage" section. + +By default, no process is bound to any worker. + +#### `enableWorkerThreads: boolean` (optional) + +By default, `jest-worker` will use `child_process` threads to spawn new Node.js processes. If you prefer [`worker_threads`](https://nodejs.org/api/worker_threads.html) instead, pass `enableWorkerThreads: true`. + +#### `exposedMethods: ReadonlyArray` (optional) + +List of method names that can be called on the child processes from the parent process. You cannot expose any method named like a public `Worker` method, or starting with `_`. If you use method auto-discovery, then these methods will not be exposed, even if they exist. + +#### `forkOptions: ForkOptions` (optional) + +Allow customizing all options passed to `child_process.fork`. By default, some values are set (`cwd`, `env`, `execArgv` and `serialization`), but you can override them and customize the rest. For a list of valid values, check [the Node documentation](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options). + +#### `idleMemoryLimit: number` (optional) + +Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/facebook/jest/issues/11956); + +After the worker has executed a task the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. If no limit is set this process does not occur. The limit can be specified in 2 ways: + +- `<= 1` - The value is assumed to be a percentage of system memory. So 0.5 sets the memory limit of the worker to half of the total system memory +- `\> 1` - Assumed to be a fixed byte value. Because of the previous rule if you wanted a value of 1 byte (I don't know why) you could use `1.1`. + +#### `maxRetries: number` (optional) + +Maximum amount of times that a dead child can be re-spawned, per call. Defaults to `3`, pass `Infinity` to allow endless retries. + +#### `numWorkers: number` (optional) + +Amount of workers to spawn. Defaults to the number of CPUs minus 1. + +#### `resourceLimits: ResourceLimits` (optional) + +The `resourceLimits` option which will be passed to `worker_threads` workers. + +#### `silent: Boolean` (optional) + +Set to false for `stdout` and `stderr` to be logged to console. + +By default this is true. + +#### `setupArgs: Array` (optional) + +The arguments that will be passed to the `setup` method during initialization. + +#### `taskQueue: TaskQueue` (optional) + +The task queue defines in which order tasks (method calls) are processed by the workers. `jest-worker` ships with a `FifoQueue` and `PriorityQueue`: + +- `FifoQueue` (default): Processes the method calls (tasks) in the call order. +- `PriorityQueue`: Processes the method calls by a computed priority in natural ordering (lower priorities first). Tasks with the same priority are processed in any order (FIFO not guaranteed). The constructor accepts a single argument, the function that is passed the name of the called function and the arguments and returns a numerical value for the priority: `new require('jest-worker').PriorityQueue((method, filename) => filename.length)`. + +#### `WorkerPool: new (workerPath: string, options?: WorkerPoolOptions) => WorkerPoolInterface` (optional) + +Provide a custom WorkerPool class to be used for spawning child processes. + +#### `workerSchedulingPolicy: 'round-robin' | 'in-order'` (optional) + +Specifies the policy how tasks are assigned to workers if multiple workers are _idle_: + +- `round-robin` (default): The task will be sequentially distributed onto the workers. The first task is assigned to the worker 1, the second to the worker 2, to ensure that the work is distributed across workers. +- `in-order`: The task will be assigned to the first free worker starting with worker 1 and only assign the work to worker 2 if the worker 1 is busy. + +Tasks are always assigned to the first free worker as soon as tasks start to queue up. The scheduling policy does not define the task scheduling which is always first-in, first-out. + +## JestWorker + +### Methods + +The returned `JestWorker` instance has all the exposed methods, plus some additional ones to interact with the workers itself: + +#### `getStdout(): Readable` + +Returns a `ReadableStream` where the standard output of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`. + +#### `getStderr(): Readable` + +Returns a `ReadableStream` where the standard error of all workers is piped. Note that the `silent` option of the child workers must be set to `true` to make it work. This is the default set by `jest-worker`, but keep it in mind when overriding options through `forkOptions`. + +#### `end()` + +Finishes the workers by killing all workers. No further calls can be done to the `Worker` instance. + +Returns a Promise that resolves with `{ forceExited: boolean }` once all workers are dead. If `forceExited` is `true`, at least one of the workers did not exit gracefully, which likely happened because it executed a leaky task that left handles open. This should be avoided, force exiting workers is a last resort to prevent creating lots of orphans. + +**Note:** + +`await`ing the `end()` Promise immediately after the workers are no longer needed before proceeding to do other useful things in your program may not be a good idea. If workers have to be force exited, `jest-worker` may go through multiple stages of force exiting (e.g. SIGTERM, later SIGKILL) and give the worker overall around 1 second time to exit on its own. During this time, your program will wait, even though it may not be necessary that all workers are dead before continuing execution. + +Consider deliberately leaving this Promise floating (unhandled resolution). After your program has done the rest of its work and is about to exit, the Node process will wait for the Promise to resolve after all workers are dead as the last event loop task. That way you parallelized computation time of your program and waiting time and you didn't delay the outputs of your program unnecessarily. + +### Worker IDs + +Each worker has a unique id (index that starts with `'1'`), which is available inside the worker as `process.env.JEST_WORKER_ID`. + +## Setting up and tearing down the child process + +The child process can define two special methods (both of them can be asynchronous): + +- `setup()`: If defined, it's executed before the first call to any method in the child. +- `teardown()`: If defined, it's executed when the farm ends. + +# More examples + +## Standard usage + +This example covers the standard usage: + +### File `parent.js` + +```js +import {Worker as JestWorker} from 'jest-worker'; + +async function main() { + const myWorker = new JestWorker(require.resolve('./worker'), { + exposedMethods: ['foo', 'bar', 'getWorkerId'], + numWorkers: 4, + }); + + console.log(await myWorker.foo('Alice')); // "Hello from foo: Alice" + console.log(await myWorker.bar('Bob')); // "Hello from bar: Bob" + console.log(await myWorker.getWorkerId()); // "3" -> this message has sent from the 3rd worker + + const {forceExited} = await myWorker.end(); + if (forceExited) { + console.error('Workers failed to exit gracefully'); + } +} + +main(); +``` + +### File `worker.js` + +```js +export function foo(param) { + return `Hello from foo: ${param}`; +} + +export function bar(param) { + return `Hello from bar: ${param}`; +} + +export function getWorkerId() { + return process.env.JEST_WORKER_ID; +} +``` + +## Bound worker usage: + +This example covers the usage with a `computeWorkerKey` method: + +### File `parent.js` + +```js +import {Worker as JestWorker} from 'jest-worker'; + +async function main() { + const myWorker = new JestWorker(require.resolve('./worker'), { + computeWorkerKey: (method, filename) => filename, + }); + + // Transform the given file, within the first available worker. + console.log(await myWorker.transform('/tmp/foo.js')); + + // Wait a bit. + await sleep(10000); + + // Transform the same file again. Will immediately return because the + // transformed file is cached in the worker, and `computeWorkerKey` ensures + // the same worker that processed the file the first time will process it now. + console.log(await myWorker.transform('/tmp/foo.js')); + + const {forceExited} = await myWorker.end(); + if (forceExited) { + console.error('Workers failed to exit gracefully'); + } +} + +main(); +``` + +### File `worker.js` + +```js +import babel from '@babel/core'; + +const cache = Object.create(null); + +export function transform(filename) { + if (cache[filename]) { + return cache[filename]; + } + + // jest-worker can handle both immediate results and thenables. If a + // thenable is returned, it will be await'ed until it resolves. + return babel.transformFileAsync(filename).then(result => { + cache[filename] = result; + + return result; + }); +} +``` diff --git a/node_modules/jest-worker/build/Farm.js b/node_modules/jest-worker/build/Farm.js new file mode 100644 index 0000000..cdcbe66 --- /dev/null +++ b/node_modules/jest-worker/build/Farm.js @@ -0,0 +1,152 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _FifoQueue = _interopRequireDefault(require('./FifoQueue')); +var _types = require('./types'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class Farm { + _computeWorkerKey; + _workerSchedulingPolicy; + _cacheKeys = Object.create(null); + _locks = []; + _offset = 0; + _taskQueue; + constructor(_numOfWorkers, _callback, options = {}) { + this._numOfWorkers = _numOfWorkers; + this._callback = _callback; + this._computeWorkerKey = options.computeWorkerKey; + this._workerSchedulingPolicy = + options.workerSchedulingPolicy ?? 'round-robin'; + this._taskQueue = options.taskQueue ?? new _FifoQueue.default(); + } + doWork(method, ...args) { + const customMessageListeners = new Set(); + const addCustomMessageListener = listener => { + customMessageListeners.add(listener); + return () => { + customMessageListeners.delete(listener); + }; + }; + const onCustomMessage = message => { + customMessageListeners.forEach(listener => listener(message)); + }; + const promise = new Promise( + // Bind args to this function so it won't reference to the parent scope. + // This prevents a memory leak in v8, because otherwise the function will + // retain args for the closure. + ((args, resolve, reject) => { + const computeWorkerKey = this._computeWorkerKey; + const request = [_types.CHILD_MESSAGE_CALL, false, method, args]; + let worker = null; + let hash = null; + if (computeWorkerKey) { + hash = computeWorkerKey.call(this, method, ...args); + worker = hash == null ? null : this._cacheKeys[hash]; + } + const onStart = worker => { + if (hash != null) { + this._cacheKeys[hash] = worker; + } + }; + const onEnd = (error, result) => { + customMessageListeners.clear(); + if (error) { + reject(error); + } else { + resolve(result); + } + }; + const task = { + onCustomMessage, + onEnd, + onStart, + request + }; + if (worker) { + this._taskQueue.enqueue(task, worker.getWorkerId()); + this._process(worker.getWorkerId()); + } else { + this._push(task); + } + }).bind(null, args) + ); + promise.UNSTABLE_onCustomMessage = addCustomMessageListener; + return promise; + } + _process(workerId) { + if (this._isLocked(workerId)) { + return this; + } + const task = this._taskQueue.dequeue(workerId); + if (!task) { + return this; + } + if (task.request[1]) { + throw new Error('Queue implementation returned processed task'); + } + + // Reference the task object outside so it won't be retained by onEnd, + // and other properties of the task object, such as task.request can be + // garbage collected. + let taskOnEnd = task.onEnd; + const onEnd = (error, result) => { + if (taskOnEnd) { + taskOnEnd(error, result); + } + taskOnEnd = null; + this._unlock(workerId); + this._process(workerId); + }; + task.request[1] = true; + this._lock(workerId); + this._callback( + workerId, + task.request, + task.onStart, + onEnd, + task.onCustomMessage + ); + return this; + } + _push(task) { + this._taskQueue.enqueue(task); + const offset = this._getNextWorkerOffset(); + for (let i = 0; i < this._numOfWorkers; i++) { + this._process((offset + i) % this._numOfWorkers); + if (task.request[1]) { + break; + } + } + return this; + } + _getNextWorkerOffset() { + switch (this._workerSchedulingPolicy) { + case 'in-order': + return 0; + case 'round-robin': + return this._offset++; + } + } + _lock(workerId) { + this._locks[workerId] = true; + } + _unlock(workerId) { + this._locks[workerId] = false; + } + _isLocked(workerId) { + return this._locks[workerId]; + } +} +exports.default = Farm; diff --git a/node_modules/jest-worker/build/FifoQueue.js b/node_modules/jest-worker/build/FifoQueue.js new file mode 100644 index 0000000..4f45bf2 --- /dev/null +++ b/node_modules/jest-worker/build/FifoQueue.js @@ -0,0 +1,89 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * First-in, First-out task queue that manages a dedicated pool + * for each worker as well as a shared queue. The FIFO ordering is guaranteed + * across the worker specific and shared queue. + */ +class FifoQueue { + _workerQueues = []; + _sharedQueue = new InternalQueue(); + enqueue(task, workerId) { + if (workerId == null) { + this._sharedQueue.enqueue(task); + return; + } + let workerQueue = this._workerQueues[workerId]; + if (workerQueue == null) { + workerQueue = this._workerQueues[workerId] = new InternalQueue(); + } + const sharedTop = this._sharedQueue.peekLast(); + const item = { + previousSharedTask: sharedTop, + task + }; + workerQueue.enqueue(item); + } + dequeue(workerId) { + const workerTop = this._workerQueues[workerId]?.peek(); + const sharedTaskIsProcessed = + workerTop?.previousSharedTask?.request[1] ?? true; + + // Process the top task from the shared queue if + // - there's no task in the worker specific queue or + // - if the non-worker-specific task after which this worker specific task + // has been queued wasn't processed yet + if (workerTop != null && sharedTaskIsProcessed) { + return this._workerQueues[workerId]?.dequeue()?.task ?? null; + } + return this._sharedQueue.dequeue(); + } +} +exports.default = FifoQueue; +/** + * FIFO queue for a single worker / shared queue. + */ +class InternalQueue { + _head = null; + _last = null; + enqueue(value) { + const item = { + next: null, + value + }; + if (this._last == null) { + this._head = item; + } else { + this._last.next = item; + } + this._last = item; + } + dequeue() { + if (this._head == null) { + return null; + } + const item = this._head; + this._head = item.next; + if (this._head == null) { + this._last = null; + } + return item.value; + } + peek() { + return this._head?.value ?? null; + } + peekLast() { + return this._last?.value ?? null; + } +} diff --git a/node_modules/jest-worker/build/PriorityQueue.js b/node_modules/jest-worker/build/PriorityQueue.js new file mode 100644 index 0000000..bba74fd --- /dev/null +++ b/node_modules/jest-worker/build/PriorityQueue.js @@ -0,0 +1,137 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Priority queue that processes tasks in natural ordering (lower priority first) + * according to the priority computed by the function passed in the constructor. + * + * FIFO ordering isn't guaranteed for tasks with the same priority. + * + * Worker specific tasks with the same priority as a non-worker specific task + * are always processed first. + */ +class PriorityQueue { + _queue = []; + _sharedQueue = new MinHeap(); + constructor(_computePriority) { + this._computePriority = _computePriority; + } + enqueue(task, workerId) { + if (workerId == null) { + this._enqueue(task, this._sharedQueue); + } else { + const queue = this._getWorkerQueue(workerId); + this._enqueue(task, queue); + } + } + _enqueue(task, queue) { + const item = { + priority: this._computePriority(task.request[2], ...task.request[3]), + task + }; + queue.add(item); + } + dequeue(workerId) { + const workerQueue = this._getWorkerQueue(workerId); + const workerTop = workerQueue.peek(); + const sharedTop = this._sharedQueue.peek(); + + // use the task from the worker queue if there's no task in the shared queue + // or if the priority of the worker queue is smaller or equal to the + // priority of the top task in the shared queue. The tasks of the + // worker specific queue are preferred because no other worker can pick this + // specific task up. + if ( + sharedTop == null || + (workerTop != null && workerTop.priority <= sharedTop.priority) + ) { + return workerQueue.poll()?.task ?? null; + } + return this._sharedQueue.poll().task; + } + _getWorkerQueue(workerId) { + let queue = this._queue[workerId]; + if (queue == null) { + queue = this._queue[workerId] = new MinHeap(); + } + return queue; + } +} +exports.default = PriorityQueue; +class MinHeap { + _heap = []; + peek() { + return this._heap[0] ?? null; + } + add(item) { + const nodes = this._heap; + nodes.push(item); + if (nodes.length === 1) { + return; + } + let currentIndex = nodes.length - 1; + + // Bubble up the added node as long as the parent is bigger + while (currentIndex > 0) { + const parentIndex = Math.floor((currentIndex + 1) / 2) - 1; + const parent = nodes[parentIndex]; + if (parent.priority <= item.priority) { + break; + } + nodes[currentIndex] = parent; + nodes[parentIndex] = item; + currentIndex = parentIndex; + } + } + poll() { + const nodes = this._heap; + const result = nodes[0]; + const lastElement = nodes.pop(); + + // heap was empty or removed the last element + if (result == null || nodes.length === 0) { + return result ?? null; + } + let index = 0; + nodes[0] = lastElement ?? null; + const element = nodes[0]; + while (true) { + let swapIndex = null; + const rightChildIndex = (index + 1) * 2; + const leftChildIndex = rightChildIndex - 1; + const rightChild = nodes[rightChildIndex]; + const leftChild = nodes[leftChildIndex]; + + // if the left child is smaller, swap with the left + if (leftChild != null && leftChild.priority < element.priority) { + swapIndex = leftChildIndex; + } + + // If the right child is smaller or the right child is smaller than the left + // then swap with the right child + if ( + rightChild != null && + rightChild.priority < (swapIndex == null ? element : leftChild).priority + ) { + swapIndex = rightChildIndex; + } + if (swapIndex == null) { + break; + } + nodes[index] = nodes[swapIndex]; + nodes[swapIndex] = element; + index = swapIndex; + } + return result; + } +} diff --git a/node_modules/jest-worker/build/WorkerPool.js b/node_modules/jest-worker/build/WorkerPool.js new file mode 100644 index 0000000..7efd526 --- /dev/null +++ b/node_modules/jest-worker/build/WorkerPool.js @@ -0,0 +1,33 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +var _BaseWorkerPool = _interopRequireDefault(require('./base/BaseWorkerPool')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class WorkerPool extends _BaseWorkerPool.default { + send(workerId, request, onStart, onEnd, onCustomMessage) { + this.getWorkerById(workerId).send(request, onStart, onEnd, onCustomMessage); + } + createWorker(workerOptions) { + let Worker; + if (this._options.enableWorkerThreads) { + Worker = require('./workers/NodeThreadsWorker').default; + } else { + Worker = require('./workers/ChildProcessWorker').default; + } + return new Worker(workerOptions); + } +} +var _default = WorkerPool; +exports.default = _default; diff --git a/node_modules/jest-worker/build/base/BaseWorkerPool.js b/node_modules/jest-worker/build/base/BaseWorkerPool.js new file mode 100644 index 0000000..1cc3556 --- /dev/null +++ b/node_modules/jest-worker/build/base/BaseWorkerPool.js @@ -0,0 +1,116 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _mergeStream() { + const data = _interopRequireDefault(require('merge-stream')); + _mergeStream = function () { + return data; + }; + return data; +} +var _types = require('../types'); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// How long to wait for the child process to terminate +// after CHILD_MESSAGE_END before sending force exiting. +const FORCE_EXIT_DELAY = 500; + +/* istanbul ignore next */ +// eslint-disable-next-line @typescript-eslint/no-empty-function +const emptyMethod = () => {}; +class BaseWorkerPool { + _stderr; + _stdout; + _options; + _workers; + constructor(workerPath, options) { + this._options = options; + this._workers = new Array(options.numWorkers); + const stdout = (0, _mergeStream().default)(); + const stderr = (0, _mergeStream().default)(); + const {forkOptions, maxRetries, resourceLimits, setupArgs} = options; + for (let i = 0; i < options.numWorkers; i++) { + const workerOptions = { + forkOptions, + idleMemoryLimit: this._options.idleMemoryLimit, + maxRetries, + resourceLimits, + setupArgs, + workerId: i, + workerPath + }; + const worker = this.createWorker(workerOptions); + const workerStdout = worker.getStdout(); + const workerStderr = worker.getStderr(); + if (workerStdout) { + stdout.add(workerStdout); + } + if (workerStderr) { + stderr.add(workerStderr); + } + this._workers[i] = worker; + } + this._stdout = stdout; + this._stderr = stderr; + } + getStderr() { + return this._stderr; + } + getStdout() { + return this._stdout; + } + getWorkers() { + return this._workers; + } + getWorkerById(workerId) { + return this._workers[workerId]; + } + createWorker(_workerOptions) { + throw Error('Missing method createWorker in WorkerPool'); + } + async end() { + // We do not cache the request object here. If so, it would only be only + // processed by one of the workers, and we want them all to close. + const workerExitPromises = this._workers.map(async worker => { + worker.send( + [_types.CHILD_MESSAGE_END, false], + emptyMethod, + emptyMethod, + emptyMethod + ); + + // Schedule a force exit in case worker fails to exit gracefully so + // await worker.waitForExit() never takes longer than FORCE_EXIT_DELAY + let forceExited = false; + const forceExitTimeout = setTimeout(() => { + worker.forceExit(); + forceExited = true; + }, FORCE_EXIT_DELAY); + await worker.waitForExit(); + // Worker ideally exited gracefully, don't send force exit then + clearTimeout(forceExitTimeout); + return forceExited; + }); + const workerExits = await Promise.all(workerExitPromises); + return workerExits.reduce( + (result, forceExited) => ({ + forceExited: result.forceExited || forceExited + }), + { + forceExited: false + } + ); + } +} +exports.default = BaseWorkerPool; diff --git a/node_modules/jest-worker/build/index.d.ts b/node_modules/jest-worker/build/index.d.ts new file mode 100644 index 0000000..1ef2c5e --- /dev/null +++ b/node_modules/jest-worker/build/index.d.ts @@ -0,0 +1,348 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +/// + +import type {ForkOptions} from 'child_process'; +import type {ResourceLimits} from 'worker_threads'; + +declare const CHILD_MESSAGE_CALL = 1; + +declare const CHILD_MESSAGE_END = 2; + +declare const CHILD_MESSAGE_INITIALIZE = 0; + +declare const CHILD_MESSAGE_MEM_USAGE = 3; + +declare type ChildMessage = + | ChildMessageInitialize + | ChildMessageCall + | ChildMessageEnd + | ChildMessageMemUsage; + +declare type ChildMessageCall = [ + type: typeof CHILD_MESSAGE_CALL, + isProcessed: boolean, + methodName: string, + args: Array, +]; + +declare type ChildMessageEnd = [ + type: typeof CHILD_MESSAGE_END, + isProcessed: boolean, +]; + +declare type ChildMessageInitialize = [ + type: typeof CHILD_MESSAGE_INITIALIZE, + isProcessed: boolean, + fileName: string, + setupArgs: Array, + workerId: string | undefined, +]; + +declare type ChildMessageMemUsage = [type: typeof CHILD_MESSAGE_MEM_USAGE]; + +declare type ComputeTaskPriorityCallback = ( + method: string, + ...args: Array +) => number; + +declare type ExcludeReservedKeys = Exclude; + +/** + * First-in, First-out task queue that manages a dedicated pool + * for each worker as well as a shared queue. The FIFO ordering is guaranteed + * across the worker specific and shared queue. + */ +export declare class FifoQueue implements TaskQueue { + private _workerQueues; + private readonly _sharedQueue; + enqueue(task: QueueChildMessage, workerId?: number): void; + dequeue(workerId: number): QueueChildMessage | null; +} + +declare type FunctionLike = (...args: any) => unknown; + +declare type HeapItem = { + priority: number; +}; + +export declare type JestWorkerFarm> = + Worker_2 & WorkerModule; + +export declare function messageParent( + message: unknown, + parentProcess?: NodeJS.Process, +): void; + +declare type MethodLikeKeys = { + [K in keyof T]: T[K] extends FunctionLike ? K : never; +}[keyof T]; + +declare class MinHeap { + private readonly _heap; + peek(): TItem | null; + add(item: TItem): void; + poll(): TItem | null; +} + +declare type OnCustomMessage = (message: Array | unknown) => void; + +declare type OnEnd = (err: Error | null, result: unknown) => void; + +declare type OnStart = (worker: WorkerInterface) => void; + +declare type OnStateChangeHandler = ( + state: WorkerStates, + oldState: WorkerStates, +) => void; + +declare type PoolExitResult = { + forceExited: boolean; +}; + +/** + * Priority queue that processes tasks in natural ordering (lower priority first) + * according to the priority computed by the function passed in the constructor. + * + * FIFO ordering isn't guaranteed for tasks with the same priority. + * + * Worker specific tasks with the same priority as a non-worker specific task + * are always processed first. + */ +export declare class PriorityQueue implements TaskQueue { + private readonly _computePriority; + private _queue; + private readonly _sharedQueue; + constructor(_computePriority: ComputeTaskPriorityCallback); + enqueue(task: QueueChildMessage, workerId?: number): void; + _enqueue(task: QueueChildMessage, queue: MinHeap): void; + dequeue(workerId: number): QueueChildMessage | null; + _getWorkerQueue(workerId: number): MinHeap; +} + +export declare interface PromiseWithCustomMessage extends Promise { + UNSTABLE_onCustomMessage?: (listener: OnCustomMessage) => () => void; +} + +declare type Promisify = ReturnType extends Promise< + infer R +> + ? (...args: Parameters) => Promise + : (...args: Parameters) => Promise>; + +declare type QueueChildMessage = { + request: ChildMessageCall; + onStart: OnStart; + onEnd: OnEnd; + onCustomMessage: OnCustomMessage; +}; + +declare type QueueItem = { + task: QueueChildMessage; + priority: number; +}; + +declare type ReservedKeys = + | 'end' + | 'getStderr' + | 'getStdout' + | 'setup' + | 'teardown'; + +export declare interface TaskQueue { + /** + * Enqueues the task in the queue for the specified worker or adds it to the + * queue shared by all workers + * @param task the task to queue + * @param workerId the id of the worker that should process this task or undefined + * if there's no preference. + */ + enqueue(task: QueueChildMessage, workerId?: number): void; + /** + * Dequeues the next item from the queue for the specified worker + * @param workerId the id of the worker for which the next task should be retrieved + */ + dequeue(workerId: number): QueueChildMessage | null; +} + +/** + * The Jest farm (publicly called "Worker") is a class that allows you to queue + * methods across multiple child processes, in order to parallelize work. This + * is done by providing an absolute path to a module that will be loaded on each + * of the child processes, and bridged to the main process. + * + * Bridged methods are specified by using the "exposedMethods" property of the + * "options" object. This is an array of strings, where each of them corresponds + * to the exported name in the loaded module. + * + * You can also control the amount of workers by using the "numWorkers" property + * of the "options" object, and the settings passed to fork the process through + * the "forkOptions" property. The amount of workers defaults to the amount of + * CPUS minus one. + * + * Queueing calls can be done in two ways: + * - Standard method: calls will be redirected to the first available worker, + * so they will get executed as soon as they can. + * + * - Sticky method: if a "computeWorkerKey" method is provided within the + * config, the resulting string of this method will be used as a key. + * Every time this key is returned, it is guaranteed that your job will be + * processed by the same worker. This is specially useful if your workers + * are caching results. + */ +declare class Worker_2 { + private _ending; + private readonly _farm; + private readonly _options; + private readonly _workerPool; + constructor(workerPath: string, options?: WorkerFarmOptions); + private _bindExposedWorkerMethods; + private _callFunctionWithArgs; + getStderr(): NodeJS.ReadableStream; + getStdout(): NodeJS.ReadableStream; + end(): Promise; +} +export {Worker_2 as Worker}; + +declare type WorkerCallback = ( + workerId: number, + request: ChildMessage, + onStart: OnStart, + onEnd: OnEnd, + onCustomMessage: OnCustomMessage, +) => void; + +declare enum WorkerEvents { + STATE_CHANGE = 'state-change', +} + +export declare type WorkerFarmOptions = { + computeWorkerKey?: (method: string, ...args: Array) => string | null; + enableWorkerThreads?: boolean; + exposedMethods?: ReadonlyArray; + forkOptions?: ForkOptions; + maxRetries?: number; + numWorkers?: number; + resourceLimits?: ResourceLimits; + setupArgs?: Array; + taskQueue?: TaskQueue; + WorkerPool?: new ( + workerPath: string, + options?: WorkerPoolOptions, + ) => WorkerPoolInterface; + workerSchedulingPolicy?: WorkerSchedulingPolicy; + idleMemoryLimit?: number; +}; + +declare interface WorkerInterface { + get state(): WorkerStates; + send( + request: ChildMessage, + onProcessStart: OnStart, + onProcessEnd: OnEnd, + onCustomMessage: OnCustomMessage, + ): void; + waitForExit(): Promise; + forceExit(): void; + getWorkerId(): number; + getStderr(): NodeJS.ReadableStream | null; + getStdout(): NodeJS.ReadableStream | null; + /** + * Some system level identifier for the worker. IE, process id, thread id, etc. + */ + getWorkerSystemId(): number; + getMemoryUsage(): Promise; + /** + * Checks to see if the child worker is actually running. + */ + isWorkerRunning(): boolean; + /** + * When the worker child is started and ready to start handling requests. + * + * @remarks + * This mostly exists to help with testing so that you don't check the status + * of things like isWorkerRunning before it actually is. + */ + waitForWorkerReady(): Promise; +} + +declare type WorkerModule = { + [K in keyof T as Extract< + ExcludeReservedKeys, + MethodLikeKeys + >]: T[K] extends FunctionLike ? Promisify : never; +}; + +declare type WorkerOptions_2 = { + forkOptions: ForkOptions; + resourceLimits: ResourceLimits; + setupArgs: Array; + maxRetries: number; + workerId: number; + workerData?: unknown; + workerPath: string; + /** + * After a job has executed the memory usage it should return to. + * + * @remarks + * Note this is different from ResourceLimits in that it checks at idle, after + * a job is complete. So you could have a resource limit of 500MB but an idle + * limit of 50MB. The latter will only trigger if after a job has completed the + * memory usage hasn't returned back down under 50MB. + */ + idleMemoryLimit?: number; + /** + * This mainly exists so the path can be changed during testing. + * https://github.com/facebook/jest/issues/9543 + */ + childWorkerPath?: string; + /** + * This is useful for debugging individual tests allowing you to see + * the raw output of the worker. + */ + silent?: boolean; + /** + * Used to immediately bind event handlers. + */ + on?: { + [WorkerEvents.STATE_CHANGE]: + | OnStateChangeHandler + | ReadonlyArray; + }; +}; + +export declare interface WorkerPoolInterface { + getStderr(): NodeJS.ReadableStream; + getStdout(): NodeJS.ReadableStream; + getWorkers(): Array; + createWorker(options: WorkerOptions_2): WorkerInterface; + send: WorkerCallback; + end(): Promise; +} + +export declare type WorkerPoolOptions = { + setupArgs: Array; + forkOptions: ForkOptions; + resourceLimits: ResourceLimits; + maxRetries: number; + numWorkers: number; + enableWorkerThreads: boolean; + idleMemoryLimit?: number; +}; + +declare type WorkerSchedulingPolicy = 'round-robin' | 'in-order'; + +declare enum WorkerStates { + STARTING = 'starting', + OK = 'ok', + OUT_OF_MEMORY = 'oom', + RESTARTING = 'restarting', + SHUTTING_DOWN = 'shutting-down', + SHUT_DOWN = 'shut-down', +} + +export {}; diff --git a/node_modules/jest-worker/build/index.js b/node_modules/jest-worker/build/index.js new file mode 100644 index 0000000..31e558b --- /dev/null +++ b/node_modules/jest-worker/build/index.js @@ -0,0 +1,172 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'FifoQueue', { + enumerable: true, + get: function () { + return _FifoQueue.default; + } +}); +Object.defineProperty(exports, 'PriorityQueue', { + enumerable: true, + get: function () { + return _PriorityQueue.default; + } +}); +exports.Worker = void 0; +Object.defineProperty(exports, 'messageParent', { + enumerable: true, + get: function () { + return _messageParent.default; + } +}); +function _os() { + const data = require('os'); + _os = function () { + return data; + }; + return data; +} +function _path() { + const data = require('path'); + _path = function () { + return data; + }; + return data; +} +var _Farm = _interopRequireDefault(require('./Farm')); +var _WorkerPool = _interopRequireDefault(require('./WorkerPool')); +var _PriorityQueue = _interopRequireDefault(require('./PriorityQueue')); +var _FifoQueue = _interopRequireDefault(require('./FifoQueue')); +var _messageParent = _interopRequireDefault(require('./workers/messageParent')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function getExposedMethods(workerPath, options) { + let exposedMethods = options.exposedMethods; + + // If no methods list is given, try getting it by auto-requiring the module. + if (!exposedMethods) { + const module = require(workerPath); + exposedMethods = Object.keys(module).filter( + name => typeof module[name] === 'function' + ); + if (typeof module === 'function') { + exposedMethods = [...exposedMethods, 'default']; + } + } + return exposedMethods; +} + +/** + * The Jest farm (publicly called "Worker") is a class that allows you to queue + * methods across multiple child processes, in order to parallelize work. This + * is done by providing an absolute path to a module that will be loaded on each + * of the child processes, and bridged to the main process. + * + * Bridged methods are specified by using the "exposedMethods" property of the + * "options" object. This is an array of strings, where each of them corresponds + * to the exported name in the loaded module. + * + * You can also control the amount of workers by using the "numWorkers" property + * of the "options" object, and the settings passed to fork the process through + * the "forkOptions" property. The amount of workers defaults to the amount of + * CPUS minus one. + * + * Queueing calls can be done in two ways: + * - Standard method: calls will be redirected to the first available worker, + * so they will get executed as soon as they can. + * + * - Sticky method: if a "computeWorkerKey" method is provided within the + * config, the resulting string of this method will be used as a key. + * Every time this key is returned, it is guaranteed that your job will be + * processed by the same worker. This is specially useful if your workers + * are caching results. + */ +class Worker { + _ending; + _farm; + _options; + _workerPool; + constructor(workerPath, options) { + this._options = { + ...options + }; + this._ending = false; + if (!(0, _path().isAbsolute)(workerPath)) { + throw new Error(`'workerPath' must be absolute, got '${workerPath}'`); + } + const workerPoolOptions = { + enableWorkerThreads: this._options.enableWorkerThreads ?? false, + forkOptions: this._options.forkOptions ?? {}, + idleMemoryLimit: this._options.idleMemoryLimit, + maxRetries: this._options.maxRetries ?? 3, + numWorkers: + this._options.numWorkers ?? Math.max((0, _os().cpus)().length - 1, 1), + resourceLimits: this._options.resourceLimits ?? {}, + setupArgs: this._options.setupArgs ?? [] + }; + if (this._options.WorkerPool) { + this._workerPool = new this._options.WorkerPool( + workerPath, + workerPoolOptions + ); + } else { + this._workerPool = new _WorkerPool.default(workerPath, workerPoolOptions); + } + this._farm = new _Farm.default( + workerPoolOptions.numWorkers, + this._workerPool.send.bind(this._workerPool), + { + computeWorkerKey: this._options.computeWorkerKey, + taskQueue: this._options.taskQueue, + workerSchedulingPolicy: this._options.workerSchedulingPolicy + } + ); + this._bindExposedWorkerMethods(workerPath, this._options); + } + _bindExposedWorkerMethods(workerPath, options) { + getExposedMethods(workerPath, options).forEach(name => { + if (name.startsWith('_')) { + return; + } + + // eslint-disable-next-line no-prototype-builtins + if (this.constructor.prototype.hasOwnProperty(name)) { + throw new TypeError(`Cannot define a method called ${name}`); + } + + // @ts-expect-error: dynamic extension of the class instance is expected. + this[name] = this._callFunctionWithArgs.bind(this, name); + }); + } + _callFunctionWithArgs(method, ...args) { + if (this._ending) { + throw new Error('Farm is ended, no more calls can be done to it'); + } + return this._farm.doWork(method, ...args); + } + getStderr() { + return this._workerPool.getStderr(); + } + getStdout() { + return this._workerPool.getStdout(); + } + async end() { + if (this._ending) { + throw new Error('Farm is ended, no more calls can be done to it'); + } + this._ending = true; + return this._workerPool.end(); + } +} +exports.Worker = Worker; diff --git a/node_modules/jest-worker/build/types.js b/node_modules/jest-worker/build/types.js new file mode 100644 index 0000000..d1e23f2 --- /dev/null +++ b/node_modules/jest-worker/build/types.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.WorkerStates = + exports.WorkerEvents = + exports.PARENT_MESSAGE_SETUP_ERROR = + exports.PARENT_MESSAGE_OK = + exports.PARENT_MESSAGE_MEM_USAGE = + exports.PARENT_MESSAGE_CUSTOM = + exports.PARENT_MESSAGE_CLIENT_ERROR = + exports.CHILD_MESSAGE_MEM_USAGE = + exports.CHILD_MESSAGE_INITIALIZE = + exports.CHILD_MESSAGE_END = + exports.CHILD_MESSAGE_CALL = + void 0; +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Because of the dynamic nature of a worker communication process, all messages +// coming from any of the other processes cannot be typed. Thus, many types +// include "unknown" as a TS type, which is (unfortunately) correct here. + +const CHILD_MESSAGE_INITIALIZE = 0; +exports.CHILD_MESSAGE_INITIALIZE = CHILD_MESSAGE_INITIALIZE; +const CHILD_MESSAGE_CALL = 1; +exports.CHILD_MESSAGE_CALL = CHILD_MESSAGE_CALL; +const CHILD_MESSAGE_END = 2; +exports.CHILD_MESSAGE_END = CHILD_MESSAGE_END; +const CHILD_MESSAGE_MEM_USAGE = 3; +exports.CHILD_MESSAGE_MEM_USAGE = CHILD_MESSAGE_MEM_USAGE; +const PARENT_MESSAGE_OK = 0; +exports.PARENT_MESSAGE_OK = PARENT_MESSAGE_OK; +const PARENT_MESSAGE_CLIENT_ERROR = 1; +exports.PARENT_MESSAGE_CLIENT_ERROR = PARENT_MESSAGE_CLIENT_ERROR; +const PARENT_MESSAGE_SETUP_ERROR = 2; +exports.PARENT_MESSAGE_SETUP_ERROR = PARENT_MESSAGE_SETUP_ERROR; +const PARENT_MESSAGE_CUSTOM = 3; +exports.PARENT_MESSAGE_CUSTOM = PARENT_MESSAGE_CUSTOM; +const PARENT_MESSAGE_MEM_USAGE = 4; +exports.PARENT_MESSAGE_MEM_USAGE = PARENT_MESSAGE_MEM_USAGE; +let WorkerStates; +exports.WorkerStates = WorkerStates; +(function (WorkerStates) { + WorkerStates['STARTING'] = 'starting'; + WorkerStates['OK'] = 'ok'; + WorkerStates['OUT_OF_MEMORY'] = 'oom'; + WorkerStates['RESTARTING'] = 'restarting'; + WorkerStates['SHUTTING_DOWN'] = 'shutting-down'; + WorkerStates['SHUT_DOWN'] = 'shut-down'; +})(WorkerStates || (exports.WorkerStates = WorkerStates = {})); +let WorkerEvents; +exports.WorkerEvents = WorkerEvents; +(function (WorkerEvents) { + WorkerEvents['STATE_CHANGE'] = 'state-change'; +})(WorkerEvents || (exports.WorkerEvents = WorkerEvents = {})); diff --git a/node_modules/jest-worker/build/workers/ChildProcessWorker.js b/node_modules/jest-worker/build/workers/ChildProcessWorker.js new file mode 100644 index 0000000..09f9da0 --- /dev/null +++ b/node_modules/jest-worker/build/workers/ChildProcessWorker.js @@ -0,0 +1,448 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = exports.SIGKILL_DELAY = void 0; +function _child_process() { + const data = require('child_process'); + _child_process = function () { + return data; + }; + return data; +} +function _os() { + const data = require('os'); + _os = function () { + return data; + }; + return data; +} +function _mergeStream() { + const data = _interopRequireDefault(require('merge-stream')); + _mergeStream = function () { + return data; + }; + return data; +} +function _supportsColor() { + const data = require('supports-color'); + _supportsColor = function () { + return data; + }; + return data; +} +var _types = require('../types'); +var _WorkerAbstract = _interopRequireDefault(require('./WorkerAbstract')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const SIGNAL_BASE_EXIT_CODE = 128; +const SIGKILL_EXIT_CODE = SIGNAL_BASE_EXIT_CODE + 9; +const SIGTERM_EXIT_CODE = SIGNAL_BASE_EXIT_CODE + 15; + +// How long to wait after SIGTERM before sending SIGKILL +const SIGKILL_DELAY = 500; + +/** + * This class wraps the child process and provides a nice interface to + * communicate with. It takes care of: + * + * - Re-spawning the process if it dies. + * - Queues calls while the worker is busy. + * - Re-sends the requests if the worker blew up. + * + * The reason for queueing them here (since childProcess.send also has an + * internal queue) is because the worker could be doing asynchronous work, and + * this would lead to the child process to read its receiving buffer and start a + * second call. By queueing calls here, we don't send the next call to the + * children until we receive the result of the previous one. + * + * As soon as a request starts to be processed by a worker, its "processed" + * field is changed to "true", so that other workers which might encounter the + * same call skip it. + */ +exports.SIGKILL_DELAY = SIGKILL_DELAY; +class ChildProcessWorker extends _WorkerAbstract.default { + _child; + _options; + _request; + _retries; + _onProcessEnd; + _onCustomMessage; + _stdout; + _stderr; + _stderrBuffer = []; + _memoryUsagePromise; + _resolveMemoryUsage; + _childIdleMemoryUsage; + _childIdleMemoryUsageLimit; + _memoryUsageCheck = false; + _childWorkerPath; + constructor(options) { + super(options); + this._options = options; + this._request = null; + this._stdout = null; + this._stderr = null; + this._childIdleMemoryUsage = null; + this._childIdleMemoryUsageLimit = options.idleMemoryLimit || null; + this._childWorkerPath = + options.childWorkerPath || require.resolve('./processChild'); + this.state = _types.WorkerStates.STARTING; + this.initialize(); + } + initialize() { + if ( + this.state === _types.WorkerStates.OUT_OF_MEMORY || + this.state === _types.WorkerStates.SHUTTING_DOWN || + this.state === _types.WorkerStates.SHUT_DOWN + ) { + return; + } + if (this._child && this._child.connected) { + this._child.kill('SIGKILL'); + } + this.state = _types.WorkerStates.STARTING; + const forceColor = _supportsColor().stdout + ? { + FORCE_COLOR: '1' + } + : {}; + const silent = this._options.silent ?? true; + if (!silent) { + // NOTE: Detecting an out of memory crash is independent of idle memory usage monitoring. We want to + // monitor for a crash occurring so that it can be handled as required and so we can tell the difference + // between an OOM crash and another kind of crash. We need to do this because if a worker crashes due to + // an OOM event sometimes it isn't seen by the worker pool and it just sits there waiting for the worker + // to respond and it never will. + console.warn('Unable to detect out of memory event if silent === false'); + } + this._stderrBuffer = []; + const options = { + cwd: process.cwd(), + env: { + ...process.env, + JEST_WORKER_ID: String(this._options.workerId + 1), + // 0-indexed workerId, 1-indexed JEST_WORKER_ID + ...forceColor + }, + // Suppress --debug / --inspect flags while preserving others (like --harmony). + execArgv: process.execArgv.filter(v => !/^--(debug|inspect)/.test(v)), + // default to advanced serialization in order to match worker threads + serialization: 'advanced', + silent, + ...this._options.forkOptions + }; + this._child = (0, _child_process().fork)( + this._childWorkerPath, + [], + options + ); + if (this._child.stdout) { + if (!this._stdout) { + // We need to add a permanent stream to the merged stream to prevent it + // from ending when the subprocess stream ends + this._stdout = (0, _mergeStream().default)(this._getFakeStream()); + } + this._stdout.add(this._child.stdout); + } + if (this._child.stderr) { + if (!this._stderr) { + // We need to add a permanent stream to the merged stream to prevent it + // from ending when the subprocess stream ends + this._stderr = (0, _mergeStream().default)(this._getFakeStream()); + } + this._stderr.add(this._child.stderr); + this._child.stderr.on('data', this.stderrDataHandler.bind(this)); + } + this._child.on('message', this._onMessage.bind(this)); + this._child.on('exit', this._onExit.bind(this)); + this._child.on('disconnect', this._onDisconnect.bind(this)); + this._child.send([ + _types.CHILD_MESSAGE_INITIALIZE, + false, + this._options.workerPath, + this._options.setupArgs + ]); + this._retries++; + + // If we exceeded the amount of retries, we will emulate an error reply + // coming from the child. This avoids code duplication related with cleaning + // the queue, and scheduling the next call. + if (this._retries > this._options.maxRetries) { + const error = new Error( + `Jest worker encountered ${this._retries} child process exceptions, exceeding retry limit` + ); + this._onMessage([ + _types.PARENT_MESSAGE_CLIENT_ERROR, + error.name, + error.message, + error.stack, + { + type: 'WorkerError' + } + ]); + + // Clear the request so we don't keep executing it. + this._request = null; + } + this.state = _types.WorkerStates.OK; + if (this._resolveWorkerReady) { + this._resolveWorkerReady(); + } + } + stderrDataHandler(chunk) { + if (chunk) { + this._stderrBuffer.push(Buffer.from(chunk)); + } + this._detectOutOfMemoryCrash(); + if (this.state === _types.WorkerStates.OUT_OF_MEMORY) { + this._workerReadyPromise = undefined; + this._resolveWorkerReady = undefined; + this.killChild(); + this._shutdown(); + } + } + _detectOutOfMemoryCrash() { + try { + const bufferStr = Buffer.concat(this._stderrBuffer).toString('utf8'); + if ( + bufferStr.includes('heap out of memory') || + bufferStr.includes('allocation failure;') || + bufferStr.includes('Last few GCs') + ) { + if ( + this.state === _types.WorkerStates.OK || + this.state === _types.WorkerStates.STARTING + ) { + this.state = _types.WorkerStates.OUT_OF_MEMORY; + } + } + } catch (err) { + console.error('Error looking for out of memory crash', err); + } + } + _onDisconnect() { + this._workerReadyPromise = undefined; + this._resolveWorkerReady = undefined; + this._detectOutOfMemoryCrash(); + if (this.state === _types.WorkerStates.OUT_OF_MEMORY) { + this.killChild(); + this._shutdown(); + } + } + _onMessage(response) { + // TODO: Add appropriate type check + let error; + switch (response[0]) { + case _types.PARENT_MESSAGE_OK: + this._onProcessEnd(null, response[1]); + break; + case _types.PARENT_MESSAGE_CLIENT_ERROR: + error = response[4]; + if (error != null && typeof error === 'object') { + const extra = error; + // @ts-expect-error: no index + const NativeCtor = globalThis[response[1]]; + const Ctor = typeof NativeCtor === 'function' ? NativeCtor : Error; + error = new Ctor(response[2]); + error.type = response[1]; + error.stack = response[3]; + for (const key in extra) { + error[key] = extra[key]; + } + } + this._onProcessEnd(error, null); + break; + case _types.PARENT_MESSAGE_SETUP_ERROR: + error = new Error(`Error when calling setup: ${response[2]}`); + error.type = response[1]; + error.stack = response[3]; + this._onProcessEnd(error, null); + break; + case _types.PARENT_MESSAGE_CUSTOM: + this._onCustomMessage(response[1]); + break; + case _types.PARENT_MESSAGE_MEM_USAGE: + this._childIdleMemoryUsage = response[1]; + if (this._resolveMemoryUsage) { + this._resolveMemoryUsage(response[1]); + this._resolveMemoryUsage = undefined; + this._memoryUsagePromise = undefined; + } + this._performRestartIfRequired(); + break; + default: + throw new TypeError(`Unexpected response from worker: ${response[0]}`); + } + } + _performRestartIfRequired() { + if (this._memoryUsageCheck) { + this._memoryUsageCheck = false; + let limit = this._childIdleMemoryUsageLimit; + + // TODO: At some point it would make sense to make use of + // stringToBytes found in jest-config, however as this + // package does not have any dependencies on an other jest + // packages that can wait until some other time. + if (limit && limit > 0 && limit <= 1) { + limit = Math.floor((0, _os().totalmem)() * limit); + } else if (limit) { + limit = Math.floor(limit); + } + if ( + limit && + this._childIdleMemoryUsage && + this._childIdleMemoryUsage > limit + ) { + this.state = _types.WorkerStates.RESTARTING; + this.killChild(); + } + } + } + _onExit(exitCode) { + this._workerReadyPromise = undefined; + this._resolveWorkerReady = undefined; + this._detectOutOfMemoryCrash(); + if (exitCode !== 0 && this.state === _types.WorkerStates.OUT_OF_MEMORY) { + this._onProcessEnd( + new Error('Jest worker ran out of memory and crashed'), + null + ); + this._shutdown(); + } else if ( + (exitCode !== 0 && + exitCode !== null && + exitCode !== SIGTERM_EXIT_CODE && + exitCode !== SIGKILL_EXIT_CODE && + this.state !== _types.WorkerStates.SHUTTING_DOWN) || + this.state === _types.WorkerStates.RESTARTING + ) { + this.state = _types.WorkerStates.RESTARTING; + this.initialize(); + if (this._request) { + this._child.send(this._request); + } + } else { + this._shutdown(); + } + } + send(request, onProcessStart, onProcessEnd, onCustomMessage) { + this._stderrBuffer = []; + onProcessStart(this); + this._onProcessEnd = (...args) => { + const hasRequest = !!this._request; + + // Clean the request to avoid sending past requests to workers that fail + // while waiting for a new request (timers, unhandled rejections...) + this._request = null; + if ( + this._childIdleMemoryUsageLimit && + this._child.connected && + hasRequest + ) { + this.checkMemoryUsage(); + } + return onProcessEnd(...args); + }; + this._onCustomMessage = (...arg) => onCustomMessage(...arg); + this._request = request; + this._retries = 0; + // eslint-disable-next-line @typescript-eslint/no-empty-function + this._child.send(request, () => {}); + } + waitForExit() { + return this._exitPromise; + } + killChild() { + // We store a reference so that there's no way we can accidentally + // kill a new worker that has been spawned. + const childToKill = this._child; + childToKill.kill('SIGTERM'); + return setTimeout(() => childToKill.kill('SIGKILL'), SIGKILL_DELAY); + } + forceExit() { + this.state = _types.WorkerStates.SHUTTING_DOWN; + const sigkillTimeout = this.killChild(); + this._exitPromise.then(() => clearTimeout(sigkillTimeout)); + } + getWorkerId() { + return this._options.workerId; + } + + /** + * Gets the process id of the worker. + * + * @returns Process id. + */ + getWorkerSystemId() { + return this._child.pid; + } + getStdout() { + return this._stdout; + } + getStderr() { + return this._stderr; + } + + /** + * Gets the last reported memory usage. + * + * @returns Memory usage in bytes. + */ + getMemoryUsage() { + if (!this._memoryUsagePromise) { + let rejectCallback; + const promise = new Promise((resolve, reject) => { + this._resolveMemoryUsage = resolve; + rejectCallback = reject; + }); + this._memoryUsagePromise = promise; + if (!this._child.connected && rejectCallback) { + rejectCallback(new Error('Child process is not running.')); + this._memoryUsagePromise = undefined; + this._resolveMemoryUsage = undefined; + return promise; + } + this._child.send([_types.CHILD_MESSAGE_MEM_USAGE], err => { + if (err && rejectCallback) { + this._memoryUsagePromise = undefined; + this._resolveMemoryUsage = undefined; + rejectCallback(err); + } + }); + return promise; + } + return this._memoryUsagePromise; + } + + /** + * Gets updated memory usage and restarts if required + */ + checkMemoryUsage() { + if (this._childIdleMemoryUsageLimit) { + this._memoryUsageCheck = true; + this._child.send([_types.CHILD_MESSAGE_MEM_USAGE], err => { + if (err) { + console.error('Unable to check memory usage', err); + } + }); + } else { + console.warn( + 'Memory usage of workers can only be checked if a limit is set' + ); + } + } + isWorkerRunning() { + return this._child.connected && !this._child.killed; + } +} +exports.default = ChildProcessWorker; diff --git a/node_modules/jest-worker/build/workers/NodeThreadsWorker.js b/node_modules/jest-worker/build/workers/NodeThreadsWorker.js new file mode 100644 index 0000000..2a7c917 --- /dev/null +++ b/node_modules/jest-worker/build/workers/NodeThreadsWorker.js @@ -0,0 +1,345 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _os() { + const data = require('os'); + _os = function () { + return data; + }; + return data; +} +function _worker_threads() { + const data = require('worker_threads'); + _worker_threads = function () { + return data; + }; + return data; +} +function _mergeStream() { + const data = _interopRequireDefault(require('merge-stream')); + _mergeStream = function () { + return data; + }; + return data; +} +var _types = require('../types'); +var _WorkerAbstract = _interopRequireDefault(require('./WorkerAbstract')); +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : {default: obj}; +} +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class ExperimentalWorker extends _WorkerAbstract.default { + _worker; + _options; + _request; + _retries; + _onProcessEnd; + _onCustomMessage; + _stdout; + _stderr; + _memoryUsagePromise; + _resolveMemoryUsage; + _childWorkerPath; + _childIdleMemoryUsage; + _childIdleMemoryUsageLimit; + _memoryUsageCheck = false; + constructor(options) { + super(options); + this._options = options; + this._request = null; + this._stdout = null; + this._stderr = null; + this._childWorkerPath = + options.childWorkerPath || require.resolve('./threadChild'); + this._childIdleMemoryUsage = null; + this._childIdleMemoryUsageLimit = options.idleMemoryLimit || null; + this.initialize(); + } + initialize() { + if ( + this.state === _types.WorkerStates.OUT_OF_MEMORY || + this.state === _types.WorkerStates.SHUTTING_DOWN || + this.state === _types.WorkerStates.SHUT_DOWN + ) { + return; + } + if (this._worker) { + this._worker.terminate(); + } + this.state = _types.WorkerStates.STARTING; + this._worker = new (_worker_threads().Worker)(this._childWorkerPath, { + eval: false, + resourceLimits: this._options.resourceLimits, + stderr: true, + stdout: true, + workerData: this._options.workerData, + ...this._options.forkOptions + }); + if (this._worker.stdout) { + if (!this._stdout) { + // We need to add a permanent stream to the merged stream to prevent it + // from ending when the subprocess stream ends + this._stdout = (0, _mergeStream().default)(this._getFakeStream()); + } + this._stdout.add(this._worker.stdout); + } + if (this._worker.stderr) { + if (!this._stderr) { + // We need to add a permanent stream to the merged stream to prevent it + // from ending when the subprocess stream ends + this._stderr = (0, _mergeStream().default)(this._getFakeStream()); + } + this._stderr.add(this._worker.stderr); + } + + // This can be useful for debugging. + if (!(this._options.silent ?? true)) { + this._worker.stdout.setEncoding('utf8'); + // eslint-disable-next-line no-console + this._worker.stdout.on('data', console.log); + this._worker.stderr.setEncoding('utf8'); + this._worker.stderr.on('data', console.error); + } + this._worker.on('message', this._onMessage.bind(this)); + this._worker.on('exit', this._onExit.bind(this)); + this._worker.on('error', this._onError.bind(this)); + this._worker.postMessage([ + _types.CHILD_MESSAGE_INITIALIZE, + false, + this._options.workerPath, + this._options.setupArgs, + String(this._options.workerId + 1) // 0-indexed workerId, 1-indexed JEST_WORKER_ID + ]); + + this._retries++; + + // If we exceeded the amount of retries, we will emulate an error reply + // coming from the child. This avoids code duplication related with cleaning + // the queue, and scheduling the next call. + if (this._retries > this._options.maxRetries) { + const error = new Error('Call retries were exceeded'); + this._onMessage([ + _types.PARENT_MESSAGE_CLIENT_ERROR, + error.name, + error.message, + error.stack, + { + type: 'WorkerError' + } + ]); + } + this.state = _types.WorkerStates.OK; + if (this._resolveWorkerReady) { + this._resolveWorkerReady(); + } + } + _onError(error) { + if (error.message.includes('heap out of memory')) { + this.state = _types.WorkerStates.OUT_OF_MEMORY; + + // Threads don't behave like processes, they don't crash when they run out of + // memory. But for consistency we want them to behave like processes so we call + // terminate to simulate a crash happening that was not planned + this._worker.terminate(); + } + } + _onMessage(response) { + let error; + switch (response[0]) { + case _types.PARENT_MESSAGE_OK: + this._onProcessEnd(null, response[1]); + break; + case _types.PARENT_MESSAGE_CLIENT_ERROR: + error = response[4]; + if (error != null && typeof error === 'object') { + const extra = error; + // @ts-expect-error: no index + const NativeCtor = globalThis[response[1]]; + const Ctor = typeof NativeCtor === 'function' ? NativeCtor : Error; + error = new Ctor(response[2]); + error.type = response[1]; + error.stack = response[3]; + for (const key in extra) { + // @ts-expect-error: no index + error[key] = extra[key]; + } + } + this._onProcessEnd(error, null); + break; + case _types.PARENT_MESSAGE_SETUP_ERROR: + error = new Error(`Error when calling setup: ${response[2]}`); + + // @ts-expect-error: adding custom properties to errors. + error.type = response[1]; + error.stack = response[3]; + this._onProcessEnd(error, null); + break; + case _types.PARENT_MESSAGE_CUSTOM: + this._onCustomMessage(response[1]); + break; + case _types.PARENT_MESSAGE_MEM_USAGE: + this._childIdleMemoryUsage = response[1]; + if (this._resolveMemoryUsage) { + this._resolveMemoryUsage(response[1]); + this._resolveMemoryUsage = undefined; + this._memoryUsagePromise = undefined; + } + this._performRestartIfRequired(); + break; + default: + throw new TypeError(`Unexpected response from worker: ${response[0]}`); + } + } + _onExit(exitCode) { + this._workerReadyPromise = undefined; + this._resolveWorkerReady = undefined; + if (exitCode !== 0 && this.state === _types.WorkerStates.OUT_OF_MEMORY) { + this._onProcessEnd( + new Error('Jest worker ran out of memory and crashed'), + null + ); + this._shutdown(); + } else if ( + (exitCode !== 0 && + this.state !== _types.WorkerStates.SHUTTING_DOWN && + this.state !== _types.WorkerStates.SHUT_DOWN) || + this.state === _types.WorkerStates.RESTARTING + ) { + this.initialize(); + if (this._request) { + this._worker.postMessage(this._request); + } + } else { + this._shutdown(); + } + } + waitForExit() { + return this._exitPromise; + } + forceExit() { + this.state = _types.WorkerStates.SHUTTING_DOWN; + this._worker.terminate(); + } + send(request, onProcessStart, onProcessEnd, onCustomMessage) { + onProcessStart(this); + this._onProcessEnd = (...args) => { + const hasRequest = !!this._request; + + // Clean the request to avoid sending past requests to workers that fail + // while waiting for a new request (timers, unhandled rejections...) + this._request = null; + if (this._childIdleMemoryUsageLimit && hasRequest) { + this.checkMemoryUsage(); + } + const res = onProcessEnd?.(...args); + + // Clean up the reference so related closures can be garbage collected. + onProcessEnd = null; + return res; + }; + this._onCustomMessage = (...arg) => onCustomMessage(...arg); + this._request = request; + this._retries = 0; + this._worker.postMessage(request); + } + getWorkerId() { + return this._options.workerId; + } + getStdout() { + return this._stdout; + } + getStderr() { + return this._stderr; + } + _performRestartIfRequired() { + if (this._memoryUsageCheck) { + this._memoryUsageCheck = false; + let limit = this._childIdleMemoryUsageLimit; + + // TODO: At some point it would make sense to make use of + // stringToBytes found in jest-config, however as this + // package does not have any dependencies on an other jest + // packages that can wait until some other time. + if (limit && limit > 0 && limit <= 1) { + limit = Math.floor((0, _os().totalmem)() * limit); + } else if (limit) { + limit = Math.floor(limit); + } + if ( + limit && + this._childIdleMemoryUsage && + this._childIdleMemoryUsage > limit + ) { + this.state = _types.WorkerStates.RESTARTING; + this._worker.terminate(); + } + } + } + + /** + * Gets the last reported memory usage. + * + * @returns Memory usage in bytes. + */ + getMemoryUsage() { + if (!this._memoryUsagePromise) { + let rejectCallback; + const promise = new Promise((resolve, reject) => { + this._resolveMemoryUsage = resolve; + rejectCallback = reject; + }); + this._memoryUsagePromise = promise; + if (!this._worker.threadId) { + rejectCallback(new Error('Child process is not running.')); + this._memoryUsagePromise = undefined; + this._resolveMemoryUsage = undefined; + return promise; + } + try { + this._worker.postMessage([_types.CHILD_MESSAGE_MEM_USAGE]); + } catch (err) { + this._memoryUsagePromise = undefined; + this._resolveMemoryUsage = undefined; + rejectCallback(err); + } + return promise; + } + return this._memoryUsagePromise; + } + + /** + * Gets updated memory usage and restarts if required + */ + checkMemoryUsage() { + if (this._childIdleMemoryUsageLimit) { + this._memoryUsageCheck = true; + this._worker.postMessage([_types.CHILD_MESSAGE_MEM_USAGE]); + } else { + console.warn( + 'Memory usage of workers can only be checked if a limit is set' + ); + } + } + + /** + * Gets the thread id of the worker. + * + * @returns Thread id. + */ + getWorkerSystemId() { + return this._worker.threadId; + } + isWorkerRunning() { + return this._worker.threadId >= 0; + } +} +exports.default = ExperimentalWorker; diff --git a/node_modules/jest-worker/build/workers/WorkerAbstract.js b/node_modules/jest-worker/build/workers/WorkerAbstract.js new file mode 100644 index 0000000..19692aa --- /dev/null +++ b/node_modules/jest-worker/build/workers/WorkerAbstract.js @@ -0,0 +1,135 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = void 0; +function _stream() { + const data = require('stream'); + _stream = function () { + return data; + }; + return data; +} +var _types = require('../types'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +class WorkerAbstract extends _stream().EventEmitter { + /** + * DO NOT WRITE TO THIS DIRECTLY. + * Use this.state getter/setters so events are emitted correctly. + */ + #state = _types.WorkerStates.STARTING; + _fakeStream = null; + _exitPromise; + _resolveExitPromise; + _workerReadyPromise; + _resolveWorkerReady; + get state() { + return this.#state; + } + set state(value) { + if (this.#state !== value) { + const oldState = this.#state; + this.#state = value; + this.emit(_types.WorkerEvents.STATE_CHANGE, value, oldState); + } + } + constructor(options) { + super(); + if (typeof options.on === 'object') { + for (const [event, handlers] of Object.entries(options.on)) { + // Can't do Array.isArray on a ReadonlyArray. + // https://github.com/microsoft/TypeScript/issues/17002 + if (typeof handlers === 'function') { + super.on(event, handlers); + } else { + for (const handler of handlers) { + super.on(event, handler); + } + } + } + } + this._exitPromise = new Promise(resolve => { + this._resolveExitPromise = resolve; + }); + this._exitPromise.then(() => { + this.state = _types.WorkerStates.SHUT_DOWN; + }); + } + + /** + * Wait for the worker child process to be ready to handle requests. + * + * @returns Promise which resolves when ready. + */ + waitForWorkerReady() { + if (!this._workerReadyPromise) { + this._workerReadyPromise = new Promise((resolve, reject) => { + let settled = false; + let to; + switch (this.state) { + case _types.WorkerStates.OUT_OF_MEMORY: + case _types.WorkerStates.SHUTTING_DOWN: + case _types.WorkerStates.SHUT_DOWN: + settled = true; + reject( + new Error( + `Worker state means it will never be ready: ${this.state}` + ) + ); + break; + case _types.WorkerStates.STARTING: + case _types.WorkerStates.RESTARTING: + this._resolveWorkerReady = () => { + settled = true; + resolve(); + if (to) { + clearTimeout(to); + } + }; + break; + case _types.WorkerStates.OK: + settled = true; + resolve(); + break; + } + if (!settled) { + to = setTimeout(() => { + if (!settled) { + reject(new Error('Timeout starting worker')); + } + }, 500); + } + }); + } + return this._workerReadyPromise; + } + + /** + * Used to shut down the current working instance once the children have been + * killed off. + */ + _shutdown() { + this.state === _types.WorkerStates.SHUT_DOWN; + + // End the permanent stream so the merged stream end too + if (this._fakeStream) { + this._fakeStream.end(); + this._fakeStream = null; + } + this._resolveExitPromise(); + } + _getFakeStream() { + if (!this._fakeStream) { + this._fakeStream = new (_stream().PassThrough)(); + } + return this._fakeStream; + } +} +exports.default = WorkerAbstract; diff --git a/node_modules/jest-worker/build/workers/messageParent.js b/node_modules/jest-worker/build/workers/messageParent.js new file mode 100644 index 0000000..cc352de --- /dev/null +++ b/node_modules/jest-worker/build/workers/messageParent.js @@ -0,0 +1,33 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +exports.default = messageParent; +function _worker_threads() { + const data = require('worker_threads'); + _worker_threads = function () { + return data; + }; + return data; +} +var _types = require('../types'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +function messageParent(message, parentProcess = process) { + if (!_worker_threads().isMainThread && _worker_threads().parentPort != null) { + _worker_threads().parentPort.postMessage([ + _types.PARENT_MESSAGE_CUSTOM, + message + ]); + } else if (typeof parentProcess.send === 'function') { + parentProcess.send([_types.PARENT_MESSAGE_CUSTOM, message]); + } else { + throw new Error('"messageParent" can only be used inside a worker'); + } +} diff --git a/node_modules/jest-worker/build/workers/processChild.js b/node_modules/jest-worker/build/workers/processChild.js new file mode 100644 index 0000000..e99eaa3 --- /dev/null +++ b/node_modules/jest-worker/build/workers/processChild.js @@ -0,0 +1,140 @@ +'use strict'; + +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _types = require('../types'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +let file = null; +let setupArgs = []; +let initialized = false; + +/** + * This file is a small bootstrapper for workers. It sets up the communication + * between the worker and the parent process, interpreting parent messages and + * sending results back. + * + * The file loaded will be lazily initialized the first time any of the workers + * is called. This is done for optimal performance: if the farm is initialized, + * but no call is made to it, child Node processes will be consuming the least + * possible amount of memory. + * + * If an invalid message is detected, the child will exit (by throwing) with a + * non-zero exit code. + */ +const messageListener = request => { + switch (request[0]) { + case _types.CHILD_MESSAGE_INITIALIZE: + const init = request; + file = init[2]; + setupArgs = init[3]; + break; + case _types.CHILD_MESSAGE_CALL: + const call = request; + execMethod(call[2], call[3]); + break; + case _types.CHILD_MESSAGE_END: + end(); + break; + case _types.CHILD_MESSAGE_MEM_USAGE: + reportMemoryUsage(); + break; + default: + throw new TypeError( + `Unexpected request from parent process: ${request[0]}` + ); + } +}; +process.on('message', messageListener); +function reportSuccess(result) { + if (!process || !process.send) { + throw new Error('Child can only be used on a forked process'); + } + process.send([_types.PARENT_MESSAGE_OK, result]); +} +function reportClientError(error) { + return reportError(error, _types.PARENT_MESSAGE_CLIENT_ERROR); +} +function reportInitializeError(error) { + return reportError(error, _types.PARENT_MESSAGE_SETUP_ERROR); +} +function reportMemoryUsage() { + if (!process || !process.send) { + throw new Error('Child can only be used on a forked process'); + } + const msg = [_types.PARENT_MESSAGE_MEM_USAGE, process.memoryUsage().heapUsed]; + process.send(msg); +} +function reportError(error, type) { + if (!process || !process.send) { + throw new Error('Child can only be used on a forked process'); + } + if (error == null) { + error = new Error('"null" or "undefined" thrown'); + } + process.send([ + type, + error.constructor && error.constructor.name, + error.message, + error.stack, + typeof error === 'object' + ? { + ...error + } + : error + ]); +} +function end() { + const main = require(file); + if (!main.teardown) { + exitProcess(); + return; + } + execFunction(main.teardown, main, [], exitProcess, exitProcess); +} +function exitProcess() { + // Clean up open handles so the process ideally exits gracefully + process.removeListener('message', messageListener); +} +function execMethod(method, args) { + const main = require(file); + let fn; + if (method === 'default') { + fn = main.__esModule ? main.default : main; + } else { + fn = main[method]; + } + function execHelper() { + execFunction(fn, main, args, reportSuccess, reportClientError); + } + if (initialized || !main.setup) { + execHelper(); + return; + } + initialized = true; + execFunction(main.setup, main, setupArgs, execHelper, reportInitializeError); +} +function execFunction(fn, ctx, args, onResult, onError) { + let result; + try { + result = fn.apply(ctx, args); + } catch (err) { + onError(err); + return; + } + if ((0, _jestUtil().isPromise)(result)) { + result.then(onResult, onError); + } else { + onResult(result); + } +} diff --git a/node_modules/jest-worker/build/workers/threadChild.js b/node_modules/jest-worker/build/workers/threadChild.js new file mode 100644 index 0000000..fc71fdd --- /dev/null +++ b/node_modules/jest-worker/build/workers/threadChild.js @@ -0,0 +1,148 @@ +'use strict'; + +function _worker_threads() { + const data = require('worker_threads'); + _worker_threads = function () { + return data; + }; + return data; +} +function _jestUtil() { + const data = require('jest-util'); + _jestUtil = function () { + return data; + }; + return data; +} +var _types = require('../types'); +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +let file = null; +let setupArgs = []; +let initialized = false; + +/** + * This file is a small bootstrapper for workers. It sets up the communication + * between the worker and the parent process, interpreting parent messages and + * sending results back. + * + * The file loaded will be lazily initialized the first time any of the workers + * is called. This is done for optimal performance: if the farm is initialized, + * but no call is made to it, child Node processes will be consuming the least + * possible amount of memory. + * + * If an invalid message is detected, the child will exit (by throwing) with a + * non-zero exit code. + */ +const messageListener = request => { + switch (request[0]) { + case _types.CHILD_MESSAGE_INITIALIZE: + const init = request; + file = init[2]; + setupArgs = init[3]; + process.env.JEST_WORKER_ID = init[4]; + break; + case _types.CHILD_MESSAGE_CALL: + const call = request; + execMethod(call[2], call[3]); + break; + case _types.CHILD_MESSAGE_END: + end(); + break; + case _types.CHILD_MESSAGE_MEM_USAGE: + reportMemoryUsage(); + break; + default: + throw new TypeError( + `Unexpected request from parent process: ${request[0]}` + ); + } +}; +_worker_threads().parentPort.on('message', messageListener); +function reportMemoryUsage() { + if (_worker_threads().isMainThread) { + throw new Error('Child can only be used on a forked process'); + } + const msg = [_types.PARENT_MESSAGE_MEM_USAGE, process.memoryUsage().heapUsed]; + _worker_threads().parentPort.postMessage(msg); +} +function reportSuccess(result) { + if (_worker_threads().isMainThread) { + throw new Error('Child can only be used on a forked process'); + } + _worker_threads().parentPort.postMessage([_types.PARENT_MESSAGE_OK, result]); +} +function reportClientError(error) { + return reportError(error, _types.PARENT_MESSAGE_CLIENT_ERROR); +} +function reportInitializeError(error) { + return reportError(error, _types.PARENT_MESSAGE_SETUP_ERROR); +} +function reportError(error, type) { + if (_worker_threads().isMainThread) { + throw new Error('Child can only be used on a forked process'); + } + if (error == null) { + error = new Error('"null" or "undefined" thrown'); + } + _worker_threads().parentPort.postMessage([ + type, + error.constructor && error.constructor.name, + error.message, + error.stack, + typeof error === 'object' + ? { + ...error + } + : error + ]); +} +function end() { + const main = require(file); + if (!main.teardown) { + exitProcess(); + return; + } + execFunction(main.teardown, main, [], exitProcess, exitProcess); +} +function exitProcess() { + // Clean up open handles so the worker ideally exits gracefully + _worker_threads().parentPort.removeListener('message', messageListener); +} +function execMethod(method, args) { + const main = require(file); + let fn; + if (method === 'default') { + fn = main.__esModule ? main.default : main; + } else { + fn = main[method]; + } + function execHelper() { + execFunction(fn, main, args, reportSuccess, reportClientError); + } + if (initialized || !main.setup) { + execHelper(); + return; + } + initialized = true; + execFunction(main.setup, main, setupArgs, execHelper, reportInitializeError); +} +function execFunction(fn, ctx, args, onResult, onError) { + let result; + try { + result = fn.apply(ctx, args); + } catch (err) { + onError(err); + return; + } + if ((0, _jestUtil().isPromise)(result)) { + result.then(onResult, onError); + } else { + onResult(result); + } +} diff --git a/node_modules/jest-worker/node_modules/supports-color/browser.js b/node_modules/jest-worker/node_modules/supports-color/browser.js new file mode 100644 index 0000000..f097aec --- /dev/null +++ b/node_modules/jest-worker/node_modules/supports-color/browser.js @@ -0,0 +1,24 @@ +/* eslint-env browser */ +'use strict'; + +function getChromeVersion() { + const matches = /(Chrome|Chromium)\/(?\d+)\./.exec(navigator.userAgent); + + if (!matches) { + return; + } + + return Number.parseInt(matches.groups.chromeVersion, 10); +} + +const colorSupport = getChromeVersion() >= 69 ? { + level: 1, + hasBasic: true, + has256: false, + has16m: false +} : false; + +module.exports = { + stdout: colorSupport, + stderr: colorSupport +}; diff --git a/node_modules/jest-worker/node_modules/supports-color/index.js b/node_modules/jest-worker/node_modules/supports-color/index.js new file mode 100644 index 0000000..2dd2fcb --- /dev/null +++ b/node_modules/jest-worker/node_modules/supports-color/index.js @@ -0,0 +1,152 @@ +'use strict'; +const os = require('os'); +const tty = require('tty'); +const hasFlag = require('has-flag'); + +const {env} = process; + +let flagForceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + flagForceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + flagForceColor = 1; +} + +function envForceColor() { + if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + return 1; + } + + if (env.FORCE_COLOR === 'false') { + return 0; + } + + return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { + const noFlagForceColor = envForceColor(); + if (noFlagForceColor !== undefined) { + flagForceColor = noFlagForceColor; + } + + const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; + + if (forceColor === 0) { + return 0; + } + + if (sniffFlags) { + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.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.release().split('.'); + if ( + 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', 'GITHUB_ACTIONS', 'BUILDKITE', 'DRONE'].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 = Number.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; + } + + return min; +} + +function getSupportLevel(stream, options = {}) { + const level = supportsColor(stream, { + streamIsTTY: stream && stream.isTTY, + ...options + }); + + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel({isTTY: tty.isatty(1)}), + stderr: getSupportLevel({isTTY: tty.isatty(2)}) +}; diff --git a/node_modules/jest-worker/node_modules/supports-color/license b/node_modules/jest-worker/node_modules/supports-color/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/jest-worker/node_modules/supports-color/license @@ -0,0 +1,9 @@ +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. diff --git a/node_modules/jest-worker/node_modules/supports-color/package.json b/node_modules/jest-worker/node_modules/supports-color/package.json new file mode 100644 index 0000000..a97bf2a --- /dev/null +++ b/node_modules/jest-worker/node_modules/supports-color/package.json @@ -0,0 +1,58 @@ +{ + "name": "supports-color", + "version": "8.1.1", + "description": "Detect whether a terminal supports color", + "license": "MIT", + "repository": "chalk/supports-color", + "funding": "https://github.com/chalk/supports-color?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js", + "browser.js" + ], + "exports": { + "node": "./index.js", + "default": "./browser.js" + }, + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "dependencies": { + "has-flag": "^4.0.0" + }, + "devDependencies": { + "ava": "^2.4.0", + "import-fresh": "^3.2.2", + "xo": "^0.35.0" + }, + "browser": "browser.js" +} diff --git a/node_modules/jest-worker/node_modules/supports-color/readme.md b/node_modules/jest-worker/node_modules/supports-color/readme.md new file mode 100644 index 0000000..3eedd1c --- /dev/null +++ b/node_modules/jest-worker/node_modules/supports-color/readme.md @@ -0,0 +1,77 @@ +# supports-color + +> Detect whether a terminal supports color + +## Install + +``` +$ npm install supports-color +``` + +## Usage + +```js +const supportsColor = require('supports-color'); + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + +## API + +Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + +### `require('supports-color').supportsColor(stream, options?)` + +Additionally, `supports-color` exposes the `.supportsColor()` function that takes an arbitrary write stream (e.g. `process.stdout`) and an optional options object to (re-)evaluate color support for an arbitrary stream. + +For example, `require('supports-color').stdout` is the equivalent of `require('supports-color').supportsColor(process.stdout)`. + +The options object supports a single boolean property `sniffFlags`. By default it is `true`, which instructs `supportsColor()` to sniff `process.argv` for the multitude of `--color` flags (see _Info_ below). If `false`, then `process.argv` is not considered when determining color support. + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + +--- + +

+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- diff --git a/node_modules/jest-worker/package.json b/node_modules/jest-worker/package.json new file mode 100644 index 0000000..84b7ca0 --- /dev/null +++ b/node_modules/jest-worker/package.json @@ -0,0 +1,41 @@ +{ + "name": "jest-worker", + "version": "29.2.1", + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest-worker" + }, + "license": "MIT", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json" + }, + "dependencies": { + "@types/node": "*", + "jest-util": "^29.2.1", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "devDependencies": { + "@tsd/typescript": "~4.8.2", + "@types/merge-stream": "^1.1.2", + "@types/supports-color": "^8.1.0", + "get-stream": "^6.0.0", + "jest-leak-detector": "^29.2.1", + "tsd-lite": "^0.6.0", + "worker-farm": "^1.6.0" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "4551c0fdd4d25b7206824957c7bcc6baf61e63bf" +} diff --git a/node_modules/jest/LICENSE b/node_modules/jest/LICENSE new file mode 100644 index 0000000..b96dcb0 --- /dev/null +++ b/node_modules/jest/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/jest/README.md b/node_modules/jest/README.md new file mode 100644 index 0000000..9c3d31e --- /dev/null +++ b/node_modules/jest/README.md @@ -0,0 +1,11 @@ +# Jest + +🃏 Delightful JavaScript Testing + +- **👩🏻‍💻 Developer Ready**: Complete and ready to set-up JavaScript testing solution. Works out of the box for any React project. + +- **🏃🏽 Instant Feedback**: Failed tests run first. Fast interactive mode can switch between running all tests or only test files related to changed files. + +- **📸 Snapshot Testing**: Jest can [capture snapshots](https://jestjs.io/docs/snapshot-testing) of React trees or other serializable values to simplify UI testing. + +Read More: https://jestjs.io/ diff --git a/node_modules/jest/bin/jest.js b/node_modules/jest/bin/jest.js new file mode 100644 index 0000000..4a82888 --- /dev/null +++ b/node_modules/jest/bin/jest.js @@ -0,0 +1,13 @@ +#!/usr/bin/env node +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +const importLocal = require('import-local'); + +if (!importLocal(__filename)) { + require('jest-cli/bin/jest'); +} diff --git a/node_modules/jest/build/index.d.ts b/node_modules/jest/build/index.d.ts new file mode 100644 index 0000000..da6592c --- /dev/null +++ b/node_modules/jest/build/index.d.ts @@ -0,0 +1,26 @@ +/** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import type {Config as Config_2} from '@jest/types'; +import {createTestScheduler} from '@jest/core'; +import {getVersion} from '@jest/core'; +import {run} from 'jest-cli'; +import {runCLI} from '@jest/core'; +import {SearchSource} from '@jest/core'; + +export declare type Config = Config_2.InitialOptions; + +export {createTestScheduler}; + +export {getVersion}; + +export {run}; + +export {runCLI}; + +export {SearchSource}; + +export {}; diff --git a/node_modules/jest/build/index.js b/node_modules/jest/build/index.js new file mode 100644 index 0000000..7d52950 --- /dev/null +++ b/node_modules/jest/build/index.js @@ -0,0 +1,49 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true +}); +Object.defineProperty(exports, 'SearchSource', { + enumerable: true, + get: function () { + return _core().SearchSource; + } +}); +Object.defineProperty(exports, 'createTestScheduler', { + enumerable: true, + get: function () { + return _core().createTestScheduler; + } +}); +Object.defineProperty(exports, 'getVersion', { + enumerable: true, + get: function () { + return _core().getVersion; + } +}); +Object.defineProperty(exports, 'run', { + enumerable: true, + get: function () { + return _jestCli().run; + } +}); +Object.defineProperty(exports, 'runCLI', { + enumerable: true, + get: function () { + return _core().runCLI; + } +}); +function _core() { + const data = require('@jest/core'); + _core = function () { + return data; + }; + return data; +} +function _jestCli() { + const data = require('jest-cli'); + _jestCli = function () { + return data; + }; + return data; +} diff --git a/node_modules/jest/package.json b/node_modules/jest/package.json new file mode 100644 index 0000000..57ad8ea --- /dev/null +++ b/node_modules/jest/package.json @@ -0,0 +1,74 @@ +{ + "name": "jest", + "description": "Delightful JavaScript Testing.", + "version": "29.2.2", + "main": "./build/index.js", + "types": "./build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./package.json": "./package.json", + "./bin/jest": "./bin/jest.js" + }, + "dependencies": { + "@jest/core": "^29.2.2", + "@jest/types": "^29.2.1", + "import-local": "^3.0.2", + "jest-cli": "^29.2.2" + }, + "devDependencies": { + "@tsd/typescript": "~4.8.2", + "tsd-lite": "^0.6.0" + }, + "peerDependencies": { + "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" + }, + "peerDependenciesMeta": { + "node-notifier": { + "optional": true + } + }, + "bin": "./bin/jest.js", + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/facebook/jest.git", + "directory": "packages/jest" + }, + "homepage": "https://jestjs.io/", + "license": "MIT", + "keywords": [ + "ava", + "babel", + "coverage", + "easy", + "expect", + "facebook", + "immersive", + "instant", + "jasmine", + "jest", + "jsdom", + "mocha", + "mocking", + "painless", + "qunit", + "runner", + "sandboxed", + "snapshot", + "tap", + "tape", + "test", + "testing", + "typescript", + "watch" + ], + "publishConfig": { + "access": "public" + }, + "gitHead": "0a8edbe0ac434394a16cc173a03ff54a9cc50e41" +} diff --git a/node_modules/js-tokens/CHANGELOG.md b/node_modules/js-tokens/CHANGELOG.md new file mode 100644 index 0000000..755e6f6 --- /dev/null +++ b/node_modules/js-tokens/CHANGELOG.md @@ -0,0 +1,151 @@ +### Version 4.0.0 (2018-01-28) ### + +- Added: Support for ES2018. The only change needed was recognizing the `s` + regex flag. +- Changed: _All_ tokens returned by the `matchToToken` function now have a + `closed` property. It is set to `undefined` for the tokens where “closed” + doesn’t make sense. This means that all tokens objects have the same shape, + which might improve performance. + +These are the breaking changes: + +- `'/a/s'.match(jsTokens)` no longer returns `['/', 'a', '/', 's']`, but + `['/a/s']`. (There are of course other variations of this.) +- Code that rely on some token objects not having the `closed` property could + now behave differently. + + +### Version 3.0.2 (2017-06-28) ### + +- No code changes. Just updates to the readme. + + +### Version 3.0.1 (2017-01-30) ### + +- Fixed: ES2015 unicode escapes with more than 6 hex digits are now matched + correctly. + + +### Version 3.0.0 (2017-01-11) ### + +This release contains one breaking change, that should [improve performance in +V8][v8-perf]: + +> So how can you, as a JavaScript developer, ensure that your RegExps are fast? +> If you are not interested in hooking into RegExp internals, make sure that +> neither the RegExp instance, nor its prototype is modified in order to get the +> best performance: +> +> ```js +> var re = /./g; +> re.exec(''); // Fast path. +> re.new_property = 'slow'; +> ``` + +This module used to export a single regex, with `.matchToToken` bolted +on, just like in the above example. This release changes the exports of +the module to avoid this issue. + +Before: + +```js +import jsTokens from "js-tokens" +// or: +var jsTokens = require("js-tokens") +var matchToToken = jsTokens.matchToToken +``` + +After: + +```js +import jsTokens, {matchToToken} from "js-tokens" +// or: +var jsTokens = require("js-tokens").default +var matchToToken = require("js-tokens").matchToToken +``` + +[v8-perf]: http://v8project.blogspot.se/2017/01/speeding-up-v8-regular-expressions.html + + +### Version 2.0.0 (2016-06-19) ### + +- Added: Support for ES2016. In other words, support for the `**` exponentiation + operator. + +These are the breaking changes: + +- `'**'.match(jsTokens)` no longer returns `['*', '*']`, but `['**']`. +- `'**='.match(jsTokens)` no longer returns `['*', '*=']`, but `['**=']`. + + +### Version 1.0.3 (2016-03-27) ### + +- Improved: Made the regex ever so slightly smaller. +- Updated: The readme. + + +### Version 1.0.2 (2015-10-18) ### + +- Improved: Limited npm package contents for a smaller download. Thanks to + @zertosh! + + +### Version 1.0.1 (2015-06-20) ### + +- Fixed: Declared an undeclared variable. + + +### Version 1.0.0 (2015-02-26) ### + +- Changed: Merged the 'operator' and 'punctuation' types into 'punctuator'. That + type is now equivalent to the Punctuator token in the ECMAScript + specification. (Backwards-incompatible change.) +- Fixed: A `-` followed by a number is now correctly matched as a punctuator + followed by a number. It used to be matched as just a number, but there is no + such thing as negative number literals. (Possibly backwards-incompatible + change.) + + +### Version 0.4.1 (2015-02-21) ### + +- Added: Support for the regex `u` flag. + + +### Version 0.4.0 (2015-02-21) ### + +- Improved: `jsTokens.matchToToken` performance. +- Added: Support for octal and binary number literals. +- Added: Support for template strings. + + +### Version 0.3.1 (2015-01-06) ### + +- Fixed: Support for unicode spaces. They used to be allowed in names (which is + very confusing), and some unicode newlines were wrongly allowed in strings and + regexes. + + +### Version 0.3.0 (2014-12-19) ### + +- Changed: The `jsTokens.names` array has been replaced with the + `jsTokens.matchToToken` function. The capturing groups of `jsTokens` are no + longer part of the public API; instead use said function. See this [gist] for + an example. (Backwards-incompatible change.) +- Changed: The empty string is now considered an “invalid” token, instead an + “empty” token (its own group). (Backwards-incompatible change.) +- Removed: component support. (Backwards-incompatible change.) + +[gist]: https://gist.github.com/lydell/be49dbf80c382c473004 + + +### Version 0.2.0 (2014-06-19) ### + +- Changed: Match ES6 function arrows (`=>`) as an operator, instead of its own + category (“functionArrow”), for simplicity. (Backwards-incompatible change.) +- Added: ES6 splats (`...`) are now matched as an operator (instead of three + punctuations). (Backwards-incompatible change.) + + +### Version 0.1.0 (2014-03-08) ### + +- Initial release. diff --git a/node_modules/js-tokens/LICENSE b/node_modules/js-tokens/LICENSE new file mode 100644 index 0000000..54aef52 --- /dev/null +++ b/node_modules/js-tokens/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/js-tokens/README.md b/node_modules/js-tokens/README.md new file mode 100644 index 0000000..00cdf16 --- /dev/null +++ b/node_modules/js-tokens/README.md @@ -0,0 +1,240 @@ +Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) +======== + +A regex that tokenizes JavaScript. + +```js +var jsTokens = require("js-tokens").default + +var jsString = "var foo=opts.foo;\n..." + +jsString.match(jsTokens) +// ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] +``` + + +Installation +============ + +`npm install js-tokens` + +```js +import jsTokens from "js-tokens" +// or: +var jsTokens = require("js-tokens").default +``` + + +Usage +===== + +### `jsTokens` ### + +A regex with the `g` flag that matches JavaScript tokens. + +The regex _always_ matches, even invalid JavaScript and the empty string. + +The next match is always directly after the previous. + +### `var token = matchToToken(match)` ### + +```js +import {matchToToken} from "js-tokens" +// or: +var matchToToken = require("js-tokens").matchToToken +``` + +Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: +String, value: String}` object. The following types are available: + +- string +- comment +- regex +- number +- name +- punctuator +- whitespace +- invalid + +Multi-line comments and strings also have a `closed` property indicating if the +token was closed or not (see below). + +Comments and strings both come in several flavors. To distinguish them, check if +the token starts with `//`, `/*`, `'`, `"` or `` ` ``. + +Names are ECMAScript IdentifierNames, that is, including both identifiers and +keywords. You may use [is-keyword-js] to tell them apart. + +Whitespace includes both line terminators and other whitespace. + +[is-keyword-js]: https://github.com/crissdev/is-keyword-js + + +ECMAScript support +================== + +The intention is to always support the latest ECMAScript version whose feature +set has been finalized. + +If adding support for a newer version requires changes, a new version with a +major verion bump will be released. + +Currently, ECMAScript 2018 is supported. + + +Invalid code handling +===================== + +Unterminated strings are still matched as strings. JavaScript strings cannot +contain (unescaped) newlines, so unterminated strings simply end at the end of +the line. Unterminated template strings can contain unescaped newlines, though, +so they go on to the end of input. + +Unterminated multi-line comments are also still matched as comments. They +simply go on to the end of the input. + +Unterminated regex literals are likely matched as division and whatever is +inside the regex. + +Invalid ASCII characters have their own capturing group. + +Invalid non-ASCII characters are treated as names, to simplify the matching of +names (except unicode spaces which are treated as whitespace). Note: See also +the [ES2018](#es2018) section. + +Regex literals may contain invalid regex syntax. They are still matched as +regex literals. They may also contain repeated regex flags, to keep the regex +simple. + +Strings may contain invalid escape sequences. + + +Limitations +=========== + +Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be +perfect. But that’s not the point either. + +You may compare jsTokens with [esprima] by using `esprima-compare.js`. +See `npm run esprima-compare`! + +[esprima]: http://esprima.org/ + +### Template string interpolation ### + +Template strings are matched as single tokens, from the starting `` ` `` to the +ending `` ` ``, including interpolations (whose tokens are not matched +individually). + +Matching template string interpolations requires recursive balancing of `{` and +`}`—something that JavaScript regexes cannot do. Only one level of nesting is +supported. + +### Division and regex literals collision ### + +Consider this example: + +```js +var g = 9.82 +var number = bar / 2/g + +var regex = / 2/g +``` + +A human can easily understand that in the `number` line we’re dealing with +division, and in the `regex` line we’re dealing with a regex literal. How come? +Because humans can look at the whole code to put the `/` characters in context. +A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also +look backwards. See the [ES2018](#es2018) section). + +When the `jsTokens` regex scans throught the above, it will see the following +at the end of both the `number` and `regex` rows: + +```js +/ 2/g +``` + +It is then impossible to know if that is a regex literal, or part of an +expression dealing with division. + +Here is a similar case: + +```js +foo /= 2/g +foo(/= 2/g) +``` + +The first line divides the `foo` variable with `2/g`. The second line calls the +`foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only +sees forwards, it cannot tell the two cases apart. + +There are some cases where we _can_ tell division and regex literals apart, +though. + +First off, we have the simple cases where there’s only one slash in the line: + +```js +var foo = 2/g +foo /= 2 +``` + +Regex literals cannot contain newlines, so the above cases are correctly +identified as division. Things are only problematic when there are more than +one non-comment slash in a single line. + +Secondly, not every character is a valid regex flag. + +```js +var number = bar / 2/e +``` + +The above example is also correctly identified as division, because `e` is not a +valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` +(any letter) as flags, but it is not worth it since it increases the amount of +ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are +allowed. This means that the above example will be identified as division as +long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 +characters long. + +Lastly, we can look _forward_ for information. + +- If the token following what looks like a regex literal is not valid after a + regex literal, but is valid in a division expression, then the regex literal + is treated as division instead. For example, a flagless regex cannot be + followed by a string, number or name, but all of those three can be the + denominator of a division. +- Generally, if what looks like a regex literal is followed by an operator, the + regex literal is treated as division instead. This is because regexes are + seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division + could likely be part of such an expression. + +Please consult the regex source and the test cases for precise information on +when regex or division is matched (should you need to know). In short, you +could sum it up as: + +If the end of a statement looks like a regex literal (even if it isn’t), it +will be treated as one. Otherwise it should work as expected (if you write sane +code). + +### ES2018 ### + +ES2018 added some nice regex improvements to the language. + +- [Unicode property escapes] should allow telling names and invalid non-ASCII + characters apart without blowing up the regex size. +- [Lookbehind assertions] should allow matching telling division and regex + literals apart in more cases. +- [Named capture groups] might simplify some things. + +These things would be nice to do, but are not critical. They probably have to +wait until the oldest maintained Node.js LTS release supports those features. + +[Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html +[Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html +[Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html + + +License +======= + +[MIT](LICENSE). diff --git a/node_modules/js-tokens/index.js b/node_modules/js-tokens/index.js new file mode 100644 index 0000000..b23a4a0 --- /dev/null +++ b/node_modules/js-tokens/index.js @@ -0,0 +1,23 @@ +// Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell +// License: MIT. (See LICENSE.) + +Object.defineProperty(exports, "__esModule", { + value: true +}) + +// This regex comes from regex.coffee, and is inserted here by generate-index.js +// (run `npm run build`). +exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g + +exports.matchToToken = function(match) { + var token = {type: "invalid", value: match[0], closed: undefined} + if (match[ 1]) token.type = "string" , token.closed = !!(match[3] || match[4]) + else if (match[ 5]) token.type = "comment" + else if (match[ 6]) token.type = "comment", token.closed = !!match[7] + else if (match[ 8]) token.type = "regex" + else if (match[ 9]) token.type = "number" + else if (match[10]) token.type = "name" + else if (match[11]) token.type = "punctuator" + else if (match[12]) token.type = "whitespace" + return token +} diff --git a/node_modules/js-tokens/package.json b/node_modules/js-tokens/package.json new file mode 100644 index 0000000..66752fa --- /dev/null +++ b/node_modules/js-tokens/package.json @@ -0,0 +1,30 @@ +{ + "name": "js-tokens", + "version": "4.0.0", + "author": "Simon Lydell", + "license": "MIT", + "description": "A regex that tokenizes JavaScript.", + "keywords": [ + "JavaScript", + "js", + "token", + "tokenize", + "regex" + ], + "files": [ + "index.js" + ], + "repository": "lydell/js-tokens", + "scripts": { + "test": "mocha --ui tdd", + "esprima-compare": "node esprima-compare ./index.js everything.js/es5.js", + "build": "node generate-index.js", + "dev": "npm run build && npm test" + }, + "devDependencies": { + "coffeescript": "2.1.1", + "esprima": "4.0.0", + "everything.js": "1.0.3", + "mocha": "5.0.0" + } +} diff --git a/node_modules/js-yaml/CHANGELOG.md b/node_modules/js-yaml/CHANGELOG.md new file mode 100644 index 0000000..b4baa4e --- /dev/null +++ b/node_modules/js-yaml/CHANGELOG.md @@ -0,0 +1,557 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [3.14.1] - 2020-12-07 +### Security +- Fix possible code execution in (already unsafe) `.load()` (in &anchor). + + +## [3.14.0] - 2020-05-22 +### Changed +- Support `safe/loadAll(input, options)` variant of call. +- CI: drop outdated nodejs versions. +- Dev deps bump. + +### Fixed +- Quote `=` in plain scalars #519. +- Check the node type for `!` tag in case user manually specifies it. +- Verify that there are no null-bytes in input. +- Fix wrong quote position when writing condensed flow, #526. + + +## [3.13.1] - 2019-04-05 +### Security +- Fix possible code execution in (already unsafe) `.load()`, #480. + + +## [3.13.0] - 2019-03-20 +### Security +- Security fix: `safeLoad()` can hang when arrays with nested refs + used as key. Now throws exception for nested arrays. #475. + + +## [3.12.2] - 2019-02-26 +### Fixed +- Fix `noArrayIndent` option for root level, #468. + + +## [3.12.1] - 2019-01-05 +### Added +- Added `noArrayIndent` option, #432. + + +## [3.12.0] - 2018-06-02 +### Changed +- Support arrow functions without a block statement, #421. + + +## [3.11.0] - 2018-03-05 +### Added +- Add arrow functions suport for `!!js/function`. + +### Fixed +- Fix dump in bin/octal/hex formats for negative integers, #399. + + +## [3.10.0] - 2017-09-10 +### Fixed +- Fix `condenseFlow` output (quote keys for sure, instead of spaces), #371, #370. +- Dump astrals as codepoints instead of surrogate pair, #368. + + +## [3.9.1] - 2017-07-08 +### Fixed +- Ensure stack is present for custom errors in node 7.+, #351. + + +## [3.9.0] - 2017-07-08 +### Added +- Add `condenseFlow` option (to create pretty URL query params), #346. + +### Fixed +- Support array return from safeLoadAll/loadAll, #350. + + +## [3.8.4] - 2017-05-08 +### Fixed +- Dumper: prevent space after dash for arrays that wrap, #343. + + +## [3.8.3] - 2017-04-05 +### Fixed +- Should not allow numbers to begin and end with underscore, #335. + + +## [3.8.2] - 2017-03-02 +### Fixed +- Fix `!!float 123` (integers) parse, #333. +- Don't allow leading zeros in floats (except 0, 0.xxx). +- Allow positive exponent without sign in floats. + + +## [3.8.1] - 2017-02-07 +### Changed +- Maintenance: update browserified build. + + +## [3.8.0] - 2017-02-07 +### Fixed +- Fix reported position for `duplicated mapping key` errors. + Now points to block start instead of block end. + (#243, thanks to @shockey). + + +## [3.7.0] - 2016-11-12 +### Added +- Support polymorphism for tags (#300, thanks to @monken). + +### Fixed +- Fix parsing of quotes followed by newlines (#304, thanks to @dplepage). + + +## [3.6.1] - 2016-05-11 +### Fixed +- Fix output cut on a pipe, #286. + + +## [3.6.0] - 2016-04-16 +### Fixed +- Dumper rewrite, fix multiple bugs with trailing `\n`. + Big thanks to @aepsilon! +- Loader: fix leading/trailing newlines in block scalars, @aepsilon. + + +## [3.5.5] - 2016-03-17 +### Fixed +- Date parse fix: don't allow dates with on digit in month and day, #268. + + +## [3.5.4] - 2016-03-09 +### Added +- `noCompatMode` for dumper, to disable quoting YAML 1.1 values. + + +## [3.5.3] - 2016-02-11 +### Changed +- Maintenance release. + + +## [3.5.2] - 2016-01-11 +### Changed +- Maintenance: missed comma in bower config. + + +## [3.5.1] - 2016-01-11 +### Changed +- Removed `inherit` dependency, #239. +- Better browserify workaround for esprima load. +- Demo rewrite. + + +## [3.5.0] - 2016-01-10 +### Fixed +- Dumper. Fold strings only, #217. +- Dumper. `norefs` option, to clone linked objects, #229. +- Loader. Throw a warning for duplicate keys, #166. +- Improved browserify support (mark `esprima` & `Buffer` excluded). + + +## [3.4.6] - 2015-11-26 +### Changed +- Use standalone `inherit` to keep browserified files clear. + + +## [3.4.5] - 2015-11-23 +### Added +- Added `lineWidth` option to dumper. + + +## [3.4.4] - 2015-11-21 +### Fixed +- Fixed floats dump (missed dot for scientific format), #220. +- Allow non-printable characters inside quoted scalars, #192. + + +## [3.4.3] - 2015-10-10 +### Changed +- Maintenance release - deps bump (esprima, argparse). + + +## [3.4.2] - 2015-09-09 +### Fixed +- Fixed serialization of duplicated entries in sequences, #205. + Thanks to @vogelsgesang. + + +## [3.4.1] - 2015-09-05 +### Fixed +- Fixed stacktrace handling in generated errors, for browsers (FF/IE). + + +## [3.4.0] - 2015-08-23 +### Changed +- Don't throw on warnings anymore. Use `onWarning` option to catch. +- Throw error on unknown tags (was warning before). +- Reworked internals of error class. + +### Fixed +- Fixed multiline keys dump, #197. Thanks to @tcr. +- Fixed heading line breaks in some scalars (regression). + + +## [3.3.1] - 2015-05-13 +### Added +- Added `.sortKeys` dumper option, thanks to @rjmunro. + +### Fixed +- Fixed astral characters support, #191. + + +## [3.3.0] - 2015-04-26 +### Changed +- Significantly improved long strings formatting in dumper, thanks to @isaacs. +- Strip BOM if exists. + + +## [3.2.7] - 2015-02-19 +### Changed +- Maintenance release. +- Updated dependencies. +- HISTORY.md -> CHANGELOG.md + + +## [3.2.6] - 2015-02-07 +### Fixed +- Fixed encoding of UTF-16 surrogate pairs. (e.g. "\U0001F431" CAT FACE). +- Fixed demo dates dump (#113, thanks to @Hypercubed). + + +## [3.2.5] - 2014-12-28 +### Fixed +- Fixed resolving of all built-in types on empty nodes. +- Fixed invalid warning on empty lines within quoted scalars and flow collections. +- Fixed bug: Tag on an empty node didn't resolve in some cases. + + +## [3.2.4] - 2014-12-19 +### Fixed +- Fixed resolving of !!null tag on an empty node. + + +## [3.2.3] - 2014-11-08 +### Fixed +- Implemented dumping of objects with circular and cross references. +- Partially fixed aliasing of constructed objects. (see issue #141 for details) + + +## [3.2.2] - 2014-09-07 +### Fixed +- Fixed infinite loop on unindented block scalars. +- Rewritten base64 encode/decode in binary type, to keep code licence clear. + + +## [3.2.1] - 2014-08-24 +### Fixed +- Nothig new. Just fix npm publish error. + + +## [3.2.0] - 2014-08-24 +### Added +- Added input piping support to CLI. + +### Fixed +- Fixed typo, that could cause hand on initial indent (#139). + + +## [3.1.0] - 2014-07-07 +### Changed +- 1.5x-2x speed boost. +- Removed deprecated `require('xxx.yml')` support. +- Significant code cleanup and refactoring. +- Internal API changed. If you used custom types - see updated examples. + Others are not affected. +- Even if the input string has no trailing line break character, + it will be parsed as if it has one. +- Added benchmark scripts. +- Moved bower files to /dist folder +- Bugfixes. + + +## [3.0.2] - 2014-02-27 +### Fixed +- Fixed bug: "constructor" string parsed as `null`. + + +## [3.0.1] - 2013-12-22 +### Fixed +- Fixed parsing of literal scalars. (issue #108) +- Prevented adding unnecessary spaces in object dumps. (issue #68) +- Fixed dumping of objects with very long (> 1024 in length) keys. + + +## [3.0.0] - 2013-12-16 +### Changed +- Refactored code. Changed API for custom types. +- Removed output colors in CLI, dump json by default. +- Removed big dependencies from browser version (esprima, buffer). Load `esprima` manually, if `!!js/function` needed. `!!bin` now returns Array in browser +- AMD support. +- Don't quote dumped strings because of `-` & `?` (if not first char). +- __Deprecated__ loading yaml files via `require()`, as not recommended + behaviour for node. + + +## [2.1.3] - 2013-10-16 +### Fixed +- Fix wrong loading of empty block scalars. + + +## [2.1.2] - 2013-10-07 +### Fixed +- Fix unwanted line breaks in folded scalars. + + +## [2.1.1] - 2013-10-02 +### Fixed +- Dumper now respects deprecated booleans syntax from YAML 1.0/1.1 +- Fixed reader bug in JSON-like sequences/mappings. + + +## [2.1.0] - 2013-06-05 +### Added +- Add standard YAML schemas: Failsafe (`FAILSAFE_SCHEMA`), + JSON (`JSON_SCHEMA`) and Core (`CORE_SCHEMA`). +- Add `skipInvalid` dumper option. + +### Changed +- Rename `DEFAULT_SCHEMA` to `DEFAULT_FULL_SCHEMA` + and `SAFE_SCHEMA` to `DEFAULT_SAFE_SCHEMA`. +- Use `safeLoad` for `require` extension. + +### Fixed +- Bug fix: export `NIL` constant from the public interface. + + +## [2.0.5] - 2013-04-26 +### Security +- Close security issue in !!js/function constructor. + Big thanks to @nealpoole for security audit. + + +## [2.0.4] - 2013-04-08 +### Changed +- Updated .npmignore to reduce package size + + +## [2.0.3] - 2013-02-26 +### Fixed +- Fixed dumping of empty arrays ans objects. ([] and {} instead of null) + + +## [2.0.2] - 2013-02-15 +### Fixed +- Fixed input validation: tabs are printable characters. + + +## [2.0.1] - 2013-02-09 +### Fixed +- Fixed error, when options not passed to function cass + + +## [2.0.0] - 2013-02-09 +### Changed +- Full rewrite. New architecture. Fast one-stage parsing. +- Changed custom types API. +- Added YAML dumper. + + +## [1.0.3] - 2012-11-05 +### Fixed +- Fixed utf-8 files loading. + + +## [1.0.2] - 2012-08-02 +### Fixed +- Pull out hand-written shims. Use ES5-Shims for old browsers support. See #44. +- Fix timstamps incorectly parsed in local time when no time part specified. + + +## [1.0.1] - 2012-07-07 +### Fixed +- Fixes `TypeError: 'undefined' is not an object` under Safari. Thanks Phuong. +- Fix timestamps incorrectly parsed in local time. Thanks @caolan. Closes #46. + + +## [1.0.0] - 2012-07-01 +### Changed +- `y`, `yes`, `n`, `no`, `on`, `off` are not converted to Booleans anymore. + Fixes #42. +- `require(filename)` now returns a single document and throws an Error if + file contains more than one document. +- CLI was merged back from js-yaml.bin + + +## [0.3.7] - 2012-02-28 +### Fixed +- Fix export of `addConstructor()`. Closes #39. + + +## [0.3.6] - 2012-02-22 +### Changed +- Removed AMD parts - too buggy to use. Need help to rewrite from scratch + +### Fixed +- Removed YUI compressor warning (renamed `double` variable). Closes #40. + + +## [0.3.5] - 2012-01-10 +### Fixed +- Workagound for .npmignore fuckup under windows. Thanks to airportyh. + + +## [0.3.4] - 2011-12-24 +### Fixed +- Fixes str[] for oldIEs support. +- Adds better has change support for browserified demo. +- improves compact output of Error. Closes #33. + + +## [0.3.3] - 2011-12-20 +### Added +- adds `compact` stringification of Errors. + +### Changed +- jsyaml executable moved to separate module. + + +## [0.3.2] - 2011-12-16 +### Added +- Added jsyaml executable. +- Added !!js/function support. Closes #12. + +### Fixed +- Fixes ug with block style scalars. Closes #26. +- All sources are passing JSLint now. +- Fixes bug in Safari. Closes #28. +- Fixes bug in Opers. Closes #29. +- Improves browser support. Closes #20. + + +## [0.3.1] - 2011-11-18 +### Added +- Added AMD support for browserified version. +- Added permalinks for online demo YAML snippets. Now we have YPaste service, lol. +- Added !!js/regexp and !!js/undefined types. Partially solves #12. + +### Changed +- Wrapped browserified js-yaml into closure. + +### Fixed +- Fixed the resolvement of non-specific tags. Closes #17. +- Fixed !!set mapping. +- Fixed month parse in dates. Closes #19. + + +## [0.3.0] - 2011-11-09 +### Added +- Added browserified version. Closes #13. +- Added live demo of browserified version. +- Ported some of the PyYAML tests. See #14. + +### Fixed +- Removed JS.Class dependency. Closes #3. +- Fixed timestamp bug when fraction was given. + + +## [0.2.2] - 2011-11-06 +### Fixed +- Fixed crash on docs without ---. Closes #8. +- Fixed multiline string parse +- Fixed tests/comments for using array as key + + +## [0.2.1] - 2011-11-02 +### Fixed +- Fixed short file read (<4k). Closes #9. + + +## [0.2.0] - 2011-11-02 +### Changed +- First public release + + +[3.14.1]: https://github.com/nodeca/js-yaml/compare/3.14.0...3.14.1 +[3.14.0]: https://github.com/nodeca/js-yaml/compare/3.13.1...3.14.0 +[3.13.1]: https://github.com/nodeca/js-yaml/compare/3.13.0...3.13.1 +[3.13.0]: https://github.com/nodeca/js-yaml/compare/3.12.2...3.13.0 +[3.12.2]: https://github.com/nodeca/js-yaml/compare/3.12.1...3.12.2 +[3.12.1]: https://github.com/nodeca/js-yaml/compare/3.12.0...3.12.1 +[3.12.0]: https://github.com/nodeca/js-yaml/compare/3.11.0...3.12.0 +[3.11.0]: https://github.com/nodeca/js-yaml/compare/3.10.0...3.11.0 +[3.10.0]: https://github.com/nodeca/js-yaml/compare/3.9.1...3.10.0 +[3.9.1]: https://github.com/nodeca/js-yaml/compare/3.9.0...3.9.1 +[3.9.0]: https://github.com/nodeca/js-yaml/compare/3.8.4...3.9.0 +[3.8.4]: https://github.com/nodeca/js-yaml/compare/3.8.3...3.8.4 +[3.8.3]: https://github.com/nodeca/js-yaml/compare/3.8.2...3.8.3 +[3.8.2]: https://github.com/nodeca/js-yaml/compare/3.8.1...3.8.2 +[3.8.1]: https://github.com/nodeca/js-yaml/compare/3.8.0...3.8.1 +[3.8.0]: https://github.com/nodeca/js-yaml/compare/3.7.0...3.8.0 +[3.7.0]: https://github.com/nodeca/js-yaml/compare/3.6.1...3.7.0 +[3.6.1]: https://github.com/nodeca/js-yaml/compare/3.6.0...3.6.1 +[3.6.0]: https://github.com/nodeca/js-yaml/compare/3.5.5...3.6.0 +[3.5.5]: https://github.com/nodeca/js-yaml/compare/3.5.4...3.5.5 +[3.5.4]: https://github.com/nodeca/js-yaml/compare/3.5.3...3.5.4 +[3.5.3]: https://github.com/nodeca/js-yaml/compare/3.5.2...3.5.3 +[3.5.2]: https://github.com/nodeca/js-yaml/compare/3.5.1...3.5.2 +[3.5.1]: https://github.com/nodeca/js-yaml/compare/3.5.0...3.5.1 +[3.5.0]: https://github.com/nodeca/js-yaml/compare/3.4.6...3.5.0 +[3.4.6]: https://github.com/nodeca/js-yaml/compare/3.4.5...3.4.6 +[3.4.5]: https://github.com/nodeca/js-yaml/compare/3.4.4...3.4.5 +[3.4.4]: https://github.com/nodeca/js-yaml/compare/3.4.3...3.4.4 +[3.4.3]: https://github.com/nodeca/js-yaml/compare/3.4.2...3.4.3 +[3.4.2]: https://github.com/nodeca/js-yaml/compare/3.4.1...3.4.2 +[3.4.1]: https://github.com/nodeca/js-yaml/compare/3.4.0...3.4.1 +[3.4.0]: https://github.com/nodeca/js-yaml/compare/3.3.1...3.4.0 +[3.3.1]: https://github.com/nodeca/js-yaml/compare/3.3.0...3.3.1 +[3.3.0]: https://github.com/nodeca/js-yaml/compare/3.2.7...3.3.0 +[3.2.7]: https://github.com/nodeca/js-yaml/compare/3.2.6...3.2.7 +[3.2.6]: https://github.com/nodeca/js-yaml/compare/3.2.5...3.2.6 +[3.2.5]: https://github.com/nodeca/js-yaml/compare/3.2.4...3.2.5 +[3.2.4]: https://github.com/nodeca/js-yaml/compare/3.2.3...3.2.4 +[3.2.3]: https://github.com/nodeca/js-yaml/compare/3.2.2...3.2.3 +[3.2.2]: https://github.com/nodeca/js-yaml/compare/3.2.1...3.2.2 +[3.2.1]: https://github.com/nodeca/js-yaml/compare/3.2.0...3.2.1 +[3.2.0]: https://github.com/nodeca/js-yaml/compare/3.1.0...3.2.0 +[3.1.0]: https://github.com/nodeca/js-yaml/compare/3.0.2...3.1.0 +[3.0.2]: https://github.com/nodeca/js-yaml/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/nodeca/js-yaml/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/nodeca/js-yaml/compare/2.1.3...3.0.0 +[2.1.3]: https://github.com/nodeca/js-yaml/compare/2.1.2...2.1.3 +[2.1.2]: https://github.com/nodeca/js-yaml/compare/2.1.1...2.1.2 +[2.1.1]: https://github.com/nodeca/js-yaml/compare/2.1.0...2.1.1 +[2.1.0]: https://github.com/nodeca/js-yaml/compare/2.0.5...2.1.0 +[2.0.5]: https://github.com/nodeca/js-yaml/compare/2.0.4...2.0.5 +[2.0.4]: https://github.com/nodeca/js-yaml/compare/2.0.3...2.0.4 +[2.0.3]: https://github.com/nodeca/js-yaml/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/nodeca/js-yaml/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/nodeca/js-yaml/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/nodeca/js-yaml/compare/1.0.3...2.0.0 +[1.0.3]: https://github.com/nodeca/js-yaml/compare/1.0.2...1.0.3 +[1.0.2]: https://github.com/nodeca/js-yaml/compare/1.0.1...1.0.2 +[1.0.1]: https://github.com/nodeca/js-yaml/compare/1.0.0...1.0.1 +[1.0.0]: https://github.com/nodeca/js-yaml/compare/0.3.7...1.0.0 +[0.3.7]: https://github.com/nodeca/js-yaml/compare/0.3.6...0.3.7 +[0.3.6]: https://github.com/nodeca/js-yaml/compare/0.3.5...0.3.6 +[0.3.5]: https://github.com/nodeca/js-yaml/compare/0.3.4...0.3.5 +[0.3.4]: https://github.com/nodeca/js-yaml/compare/0.3.3...0.3.4 +[0.3.3]: https://github.com/nodeca/js-yaml/compare/0.3.2...0.3.3 +[0.3.2]: https://github.com/nodeca/js-yaml/compare/0.3.1...0.3.2 +[0.3.1]: https://github.com/nodeca/js-yaml/compare/0.3.0...0.3.1 +[0.3.0]: https://github.com/nodeca/js-yaml/compare/0.2.2...0.3.0 +[0.2.2]: https://github.com/nodeca/js-yaml/compare/0.2.1...0.2.2 +[0.2.1]: https://github.com/nodeca/js-yaml/compare/0.2.0...0.2.1 +[0.2.0]: https://github.com/nodeca/js-yaml/releases/tag/0.2.0 diff --git a/node_modules/js-yaml/LICENSE b/node_modules/js-yaml/LICENSE new file mode 100644 index 0000000..09d3a29 --- /dev/null +++ b/node_modules/js-yaml/LICENSE @@ -0,0 +1,21 @@ +(The MIT License) + +Copyright (C) 2011-2015 by Vitaly Puzrin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION 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/js-yaml/README.md b/node_modules/js-yaml/README.md new file mode 100644 index 0000000..246e563 --- /dev/null +++ b/node_modules/js-yaml/README.md @@ -0,0 +1,299 @@ +JS-YAML - YAML 1.2 parser / writer for JavaScript +================================================= + +[![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml) +[![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) + +__[Online Demo](http://nodeca.github.com/js-yaml/)__ + + +This is an implementation of [YAML](http://yaml.org/), a human-friendly data +serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was +completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. + + +Installation +------------ + +### YAML module for node.js + +``` +npm install js-yaml +``` + + +### CLI executable + +If you want to inspect your YAML files from CLI, install js-yaml globally: + +``` +npm install -g js-yaml +``` + +#### Usage + +``` +usage: js-yaml [-h] [-v] [-c] [-t] file + +Positional arguments: + file File with YAML document(s) + +Optional arguments: + -h, --help Show this help message and exit. + -v, --version Show program's version number and exit. + -c, --compact Display errors in compact mode + -t, --trace Show stack trace on error +``` + + +### Bundled YAML library for browsers + +``` html + + + + +``` + +Browser support was done mostly for the online demo. If you find any errors - feel +free to send pull requests with fixes. Also note, that IE and other old browsers +needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. + +Notes: + +1. We have no resources to support browserified version. Don't expect it to be + well tested. Don't expect fast fixes if something goes wrong there. +2. `!!js/function` in browser bundle will not work by default. If you really need + it - load `esprima` parser first (via amd or directly). +3. `!!bin` in browser will return `Array`, because browsers do not support + node.js `Buffer` and adding Buffer shims is completely useless on practice. + + +API +--- + +Here we cover the most 'useful' methods. If you need advanced details (creating +your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and +[examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more +info. + +``` javascript +const yaml = require('js-yaml'); +const fs = require('fs'); + +// Get document, or throw exception on error +try { + const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); + console.log(doc); +} catch (e) { + console.log(e); +} +``` + + +### safeLoad (string [ , options ]) + +**Recommended loading way.** Parses `string` as single YAML document. Returns either a +plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does +not support regexps, functions and undefined. This method is safe for untrusted data. + +options: + +- `filename` _(default: null)_ - string to be used as a file path in + error/warning messages. +- `onWarning` _(default: null)_ - function to call on warning messages. + Loader will call this function with an instance of `YAMLException` for each warning. +- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. + - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: + http://www.yaml.org/spec/1.2/spec.html#id2802346 + - `JSON_SCHEMA` - all JSON-supported types: + http://www.yaml.org/spec/1.2/spec.html#id2803231 + - `CORE_SCHEMA` - same as `JSON_SCHEMA`: + http://www.yaml.org/spec/1.2/spec.html#id2804923 + - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones + (`!!js/undefined`, `!!js/regexp` and `!!js/function`): + http://yaml.org/type/ + - `DEFAULT_FULL_SCHEMA` - all supported YAML types. +- `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. + +NOTE: This function **does not** understand multi-document sources, it throws +exception on those. + +NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. +So, the JSON schema is not as strictly defined in the YAML specification. +It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. +The core schema also has no such restrictions. It allows binary notation for integers. + + +### load (string [ , options ]) + +**Use with care with untrusted sources**. The same as `safeLoad()` but uses +`DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: +`!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you +must additionally validate object structure to avoid injections: + +``` javascript +const untrusted_code = '"toString": ! "function (){very_evil_thing();}"'; + +// I'm just converting that string, what could possibly go wrong? +require('js-yaml').load(untrusted_code) + '' +``` + + +### safeLoadAll (string [, iterator] [, options ]) + +Same as `safeLoad()`, but understands multi-document sources. Applies +`iterator` to each document if specified, or returns array of documents. + +``` javascript +const yaml = require('js-yaml'); + +yaml.safeLoadAll(data, function (doc) { + console.log(doc); +}); +``` + + +### loadAll (string [, iterator] [ , options ]) + +Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. + + +### safeDump (object [ , options ]) + +Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will +throw an exception if you try to dump regexps or functions. However, you can +disable exceptions by setting the `skipInvalid` option to `true`. + +options: + +- `indent` _(default: 2)_ - indentation width to use (in spaces). +- `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements +- `skipInvalid` _(default: false)_ - do not throw on invalid types (like function + in the safe schema) and skip pairs and single values with such types. +- `flowLevel` (default: -1) - specifies level of nesting, when to switch from + block to flow style for collections. -1 means block style everwhere +- `styles` - "tag" => "style" map. Each tag may have own set of styles. +- `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. +- `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a + function, use the function to sort the keys. +- `lineWidth` _(default: `80`)_ - set max line width. +- `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references +- `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older + yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 +- `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. + +The following table show availlable styles (e.g. "canonical", +"binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml +output is shown on the right side after `=>` (default setting) or `->`: + +``` none +!!null + "canonical" -> "~" + "lowercase" => "null" + "uppercase" -> "NULL" + "camelcase" -> "Null" + +!!int + "binary" -> "0b1", "0b101010", "0b1110001111010" + "octal" -> "01", "052", "016172" + "decimal" => "1", "42", "7290" + "hexadecimal" -> "0x1", "0x2A", "0x1C7A" + +!!bool + "lowercase" => "true", "false" + "uppercase" -> "TRUE", "FALSE" + "camelcase" -> "True", "False" + +!!float + "lowercase" => ".nan", '.inf' + "uppercase" -> ".NAN", '.INF' + "camelcase" -> ".NaN", '.Inf' +``` + +Example: + +``` javascript +safeDump (object, { + 'styles': { + '!!null': 'canonical' // dump null as ~ + }, + 'sortKeys': true // sort object keys +}); +``` + +### dump (object [ , options ]) + +Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). + + +Supported YAML types +-------------------- + +The list of standard YAML tags and corresponding JavaScipt types. See also +[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and +[YAML types repository](http://yaml.org/type/). + +``` +!!null '' # null +!!bool 'yes' # bool +!!int '3...' # number +!!float '3.14...' # number +!!binary '...base64...' # buffer +!!timestamp 'YYYY-...' # date +!!omap [ ... ] # array of key-value pairs +!!pairs [ ... ] # array or array pairs +!!set { ... } # array of objects with given keys and null values +!!str '...' # string +!!seq [ ... ] # array +!!map { ... } # object +``` + +**JavaScript-specific tags** + +``` +!!js/regexp /pattern/gim # RegExp +!!js/undefined '' # Undefined +!!js/function 'function () {...}' # Function +``` + +Caveats +------- + +Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects +or arrays as keys, and stringifies (by calling `toString()` method) them at the +moment of adding them. + +``` yaml +--- +? [ foo, bar ] +: - baz +? { foo: bar } +: - baz + - baz +``` + +``` javascript +{ "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } +``` + +Also, reading of properties on implicit block mapping keys is not supported yet. +So, the following YAML document cannot be loaded. + +``` yaml +&anchor foo: + foo: bar + *anchor: duplicate key + baz: bat + *anchor: duplicate key +``` + + +js-yaml for enterprise +---------------------- + +Available as part of the Tidelift Subscription + +The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/js-yaml/bin/js-yaml.js b/node_modules/js-yaml/bin/js-yaml.js new file mode 100644 index 0000000..e79186b --- /dev/null +++ b/node_modules/js-yaml/bin/js-yaml.js @@ -0,0 +1,132 @@ +#!/usr/bin/env node + + +'use strict'; + +/*eslint-disable no-console*/ + + +// stdlib +var fs = require('fs'); + + +// 3rd-party +var argparse = require('argparse'); + + +// internal +var yaml = require('..'); + + +//////////////////////////////////////////////////////////////////////////////// + + +var cli = new argparse.ArgumentParser({ + prog: 'js-yaml', + version: require('../package.json').version, + addHelp: true +}); + + +cli.addArgument([ '-c', '--compact' ], { + help: 'Display errors in compact mode', + action: 'storeTrue' +}); + + +// deprecated (not needed after we removed output colors) +// option suppressed, but not completely removed for compatibility +cli.addArgument([ '-j', '--to-json' ], { + help: argparse.Const.SUPPRESS, + dest: 'json', + action: 'storeTrue' +}); + + +cli.addArgument([ '-t', '--trace' ], { + help: 'Show stack trace on error', + action: 'storeTrue' +}); + +cli.addArgument([ 'file' ], { + help: 'File to read, utf-8 encoded without BOM', + nargs: '?', + defaultValue: '-' +}); + + +//////////////////////////////////////////////////////////////////////////////// + + +var options = cli.parseArgs(); + + +//////////////////////////////////////////////////////////////////////////////// + +function readFile(filename, encoding, callback) { + if (options.file === '-') { + // read from stdin + + var chunks = []; + + process.stdin.on('data', function (chunk) { + chunks.push(chunk); + }); + + process.stdin.on('end', function () { + return callback(null, Buffer.concat(chunks).toString(encoding)); + }); + } else { + fs.readFile(filename, encoding, callback); + } +} + +readFile(options.file, 'utf8', function (error, input) { + var output, isYaml; + + if (error) { + if (error.code === 'ENOENT') { + console.error('File not found: ' + options.file); + process.exit(2); + } + + console.error( + options.trace && error.stack || + error.message || + String(error)); + + process.exit(1); + } + + try { + output = JSON.parse(input); + isYaml = false; + } catch (err) { + if (err instanceof SyntaxError) { + try { + output = []; + yaml.loadAll(input, function (doc) { output.push(doc); }, {}); + isYaml = true; + + if (output.length === 0) output = null; + else if (output.length === 1) output = output[0]; + + } catch (e) { + if (options.trace && err.stack) console.error(e.stack); + else console.error(e.toString(options.compact)); + + process.exit(1); + } + } else { + console.error( + options.trace && err.stack || + err.message || + String(err)); + + process.exit(1); + } + } + + if (isYaml) console.log(JSON.stringify(output, null, ' ')); + else console.log(yaml.dump(output)); +}); diff --git a/node_modules/js-yaml/dist/js-yaml.js b/node_modules/js-yaml/dist/js-yaml.js new file mode 100644 index 0000000..7878320 --- /dev/null +++ b/node_modules/js-yaml/dist/js-yaml.js @@ -0,0 +1,3989 @@ +/*! js-yaml 3.14.1 https://github.com/nodeca/js-yaml */(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsyaml = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + +function State(options) { + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// [24] b-line-feed ::= #xA /* LF */ +// [25] b-carriage-return ::= #xD /* CR */ +// [3] c-byte-order-mark ::= #xFEFF +function isNsChar(c) { + return isPrintable(c) && !isWhitespace(c) + // byte-order-mark + && c !== 0xFEFF + // b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe(c, prev) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // - ":" - "#" + // /* An ns-char preceding */ "#" + && c !== CHAR_COLON + && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable(c) && c !== 0xFEFF + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { + var i; + var char, prev_char; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(string.charCodeAt(0)) + && !isWhitespace(string.charCodeAt(string.length - 1)); + + if (singleLineOnly) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + return plain && !testAmbiguousType(string) + ? STYLE_PLAIN : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { + return "'" + string + "'"; + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; + + for (var i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). + if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { + nextChar = string.charCodeAt(i + 1); + if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { + // Combine the surrogate pair and store it escaped. + result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; + } + } + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (index !== 0) pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + state.tag = explicit ? type.tag : '?'; + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; + if (block && (state.dump.length !== 0)) { + writeBlockSequence(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey); + } + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; + + return ''; +} + +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + +module.exports.dump = dump; +module.exports.safeDump = safeDump; + +},{"./common":2,"./exception":4,"./schema/default_full":9,"./schema/default_safe":10}],4:[function(require,module,exports){ +// YAML error class. http://stackoverflow.com/questions/8458984 +// +'use strict'; + +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; + + +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; + + result += this.reason || '(unknown reason)'; + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } + + return result; +}; + + +module.exports = YAMLException; + +},{}],5:[function(require,module,exports){ +'use strict'; + +/*eslint-disable max-len,no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Mark = require('./mark'); +var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); +var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); + + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = {}, + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _pos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + _pos = state.position; + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else { + break; // Reading is done. Go to the epilogue. + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag !== null && state.tag !== '!') { + if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} + + +function safeLoadAll(input, iterator, options) { + if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; + +},{"./common":2,"./exception":4,"./mark":6,"./schema/default_full":9,"./schema/default_safe":10}],6:[function(require,module,exports){ +'use strict'; + + +var common = require('./common'); + + +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} + + +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; + + if (!this.buffer) return null; + + indent = indent || 4; + maxLength = maxLength || 75; + + head = ''; + start = this.position; + + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } + } + + tail = ''; + end = this.position; + + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } + } + + snippet = this.buffer.slice(start, end); + + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; + + +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; + + if (this.name) { + where += 'in "' + this.name + '" '; + } + + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); + + if (!compact) { + snippet = this.getSnippet(); + + if (snippet) { + where += ':\n' + snippet; + } + } + + return where; +}; + + +module.exports = Mark; + +},{"./common":2}],7:[function(require,module,exports){ +'use strict'; + +/*eslint-disable max-len*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Type = require('./type'); + + +function compileList(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); + } + }); + + result.push(currentType); + }); + + return result.filter(function (type, index) { + return exclude.indexOf(index) === -1; + }); +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; + + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; + + this.implicit.forEach(function (type) { + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} + + +Schema.DEFAULT = null; + + +Schema.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); + } + + schemas = common.toArray(schemas); + types = common.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type) { return type instanceof Type; })) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema({ + include: schemas, + explicit: types + }); +}; + + +module.exports = Schema; + +},{"./common":2,"./exception":4,"./type":13}],8:[function(require,module,exports){ +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./json') + ] +}); + +},{"../schema":7,"./json":12}],9:[function(require,module,exports){ +// JS-YAML's default schema for `load` function. +// It is not described in the YAML specification. +// +// This schema is based on JS-YAML's default safe schema and includes +// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. +// +// Also this schema is used as default base schema at `Schema.create` function. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = Schema.DEFAULT = new Schema({ + include: [ + require('./default_safe') + ], + explicit: [ + require('../type/js/undefined'), + require('../type/js/regexp'), + require('../type/js/function') + ] +}); + +},{"../schema":7,"../type/js/function":18,"../type/js/regexp":19,"../type/js/undefined":20,"./default_safe":10}],10:[function(require,module,exports){ +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./core') + ], + implicit: [ + require('../type/timestamp'), + require('../type/merge') + ], + explicit: [ + require('../type/binary'), + require('../type/omap'), + require('../type/pairs'), + require('../type/set') + ] +}); + +},{"../schema":7,"../type/binary":14,"../type/merge":22,"../type/omap":24,"../type/pairs":25,"../type/set":27,"../type/timestamp":29,"./core":8}],11:[function(require,module,exports){ +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + explicit: [ + require('../type/str'), + require('../type/seq'), + require('../type/map') + ] +}); + +},{"../schema":7,"../type/map":21,"../type/seq":26,"../type/str":28}],12:[function(require,module,exports){ +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./failsafe') + ], + implicit: [ + require('../type/null'), + require('../type/bool'), + require('../type/int'), + require('../type/float') + ] +}); + +},{"../schema":7,"../type/bool":15,"../type/float":16,"../type/int":17,"../type/null":23,"./failsafe":11}],13:[function(require,module,exports){ +'use strict'; + +var YAMLException = require('./exception'); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; + +},{"./exception":4}],14:[function(require,module,exports){ +'use strict'; + +/*eslint-disable no-bitwise*/ + +var NodeBuffer; + +try { + // A trick for browserified version, to not include `Buffer` shim + var _require = require; + NodeBuffer = _require('buffer').Buffer; +} catch (__) {} + +var Type = require('../type'); + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + // Support node 6.+ Buffer API when available + return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); + } + + return result; +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + +},{"../type":13}],15:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + +},{"../type":13}],16:[function(require,module,exports){ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign, base, digits; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); + + value = 0.0; + base = 1; + + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); + + return sign * value; + + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + +},{"../common":2,"../type":13}],17:[function(require,module,exports){ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 10 (except 0) or base 60 + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch === ':') break; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + // if !base60 - done; + if (ch !== ':') return true; + + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value, 16); + return sign * parseInt(value, 8); + } + + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); + + value = 0; + base = 1; + + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); + + return sign * value; + + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); + +},{"../common":2,"../type":13}],18:[function(require,module,exports){ +'use strict'; + +var esprima; + +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + // workaround to exclude package from browserify list. + var _require = require; + esprima = _require('esprima'); +} catch (_) { + /* eslint-disable no-redeclare */ + /* global window */ + if (typeof window !== 'undefined') esprima = window.esprima; +} + +var Type = require('../../type'); + +function resolveJavascriptFunction(data) { + if (data === null) return false; + + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + return false; + } + + return true; + } catch (err) { + return false; + } +} + +function constructJavascriptFunction(data) { + /*jslint evil:true*/ + + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + throw new Error('Failed to resolve function'); + } + + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); + + body = ast.body[0].expression.body.range; + + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + if (ast.body[0].expression.body.type === 'BlockStatement') { + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); + } + // ES6 arrow functions can omit the BlockStatement. In that case, just return + // the body. + /*eslint-disable no-new-func*/ + return new Function(params, 'return ' + source.slice(body[0], body[1])); +} + +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} + +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); + +},{"../../type":13}],19:[function(require,module,exports){ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; + + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + + if (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; + } + + return true; +} + +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // `/foo/gim` - tail can be maximum 4 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + return new RegExp(regexp, modifiers); +} + +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; + + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; + + return result; +} + +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); + +},{"../../type":13}],20:[function(require,module,exports){ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptUndefined() { + return true; +} + +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} + +function representJavascriptUndefined() { + return ''; +} + +function isUndefined(object) { + return typeof object === 'undefined'; +} + +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); + +},{"../../type":13}],21:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +},{"../type":13}],22:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + +},{"../type":13}],23:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); + +},{"../type":13}],24:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + +},{"../type":13}],25:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + +},{"../type":13}],26:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +},{"../type":13}],27:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); + +},{"../type":13}],28:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +},{"../type":13}],29:[function(require,module,exports){ +'use strict'; + +var Type = require('../type'); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + +},{"../type":13}],"/":[function(require,module,exports){ +'use strict'; + + +var yaml = require('./lib/js-yaml.js'); + + +module.exports = yaml; + +},{"./lib/js-yaml.js":1}]},{},[])("/") +}); diff --git a/node_modules/js-yaml/dist/js-yaml.min.js b/node_modules/js-yaml/dist/js-yaml.min.js new file mode 100644 index 0000000..1b6ecc1 --- /dev/null +++ b/node_modules/js-yaml/dist/js-yaml.min.js @@ -0,0 +1 @@ +/*! js-yaml 3.14.1 https://github.com/nodeca/js-yaml */!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).jsyaml=e()}(function(){return function i(r,o,a){function s(t,e){if(!o[t]){if(!r[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(c)return c(t,!0);throw(n=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",n}n=o[t]={exports:{}},r[t][0].call(n.exports,function(e){return s(r[t][1][e]||e)},n,n.exports,i,r,o,a)}return o[t].exports}for(var c="function"==typeof require&&require,e=0;e=i.flowLevel;switch(V(r,n,i.indent,t,function(e){return function(e,t){for(var n=0,i=e.implicitTypes.length;n"+z(r,i.indent)+J(U(function(t,n){var e,i=/(\n+)([^\n]*)/g,r=function(){var e=-1!==(e=t.indexOf("\n"))?e:t.length;return i.lastIndex=e,Q(t.slice(0,e),n)}(),o="\n"===t[0]||" "===t[0];for(;e=i.exec(t);){var a=e[1],s=e[2];e=" "===s[0],r+=a+(o||e||""===s?"":"\n")+Q(s,n),o=e}return r}(r,t),e));case G:return'"'+function(e){for(var t,n,i,r="",o=0;ot&&o tag resolver accepts not "'+o+'" style');i=r.represent[o](t,o)}e.dump=i}return 1}}function ee(e,t,n,i,r,o){e.tag=null,e.dump=n,X(e,n,!1)||X(e,n,!0);var a=l.call(e.dump);i=i&&(e.flowLevel<0||e.flowLevel>t);var s,c,u="[object Object]"===a||"[object Array]"===a;if(u&&(c=-1!==(s=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||c||2!==e.indent&&0 "+e.dump)}return 1}function te(e,t){var n,i,r=[],o=[];for(!function e(t,n,i){var r,o,a;if(null!==t&&"object"==typeof t)if(-1!==(o=n.indexOf(t)))-1===i.indexOf(o)&&i.push(o);else if(n.push(t),Array.isArray(t))for(o=0,a=t.length;o>10),56320+(c-65536&1023)),e.position++}else N(e,"unknown escape sequence");n=i=e.position}else S(u)?(L(e,n,i,!0),B(e,Y(e,!1,t)),n=i=e.position):e.position===e.lineStart&&R(e)?N(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}N(e,"unexpected end of the stream within a double quoted scalar")}}function K(e,t){var n,i,r=e.tag,o=e.anchor,a=[],s=!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=a),i=e.input.charCodeAt(e.position);0!==i&&45===i&&O(e.input.charCodeAt(e.position+1));)if(s=!0,e.position++,Y(e,!0,-1)&&e.lineIndent<=t)a.push(null),i=e.input.charCodeAt(e.position);else if(n=e.line,P(e,t,x,!1,!0),a.push(e.result),Y(e,!0,-1),i=e.input.charCodeAt(e.position),(e.line===n||e.lineIndent>t)&&0!==i)N(e,"bad indentation of a sequence entry");else if(e.lineIndentt?p=1:e.lineIndent===t?p=0:e.lineIndentt?p=1:e.lineIndent===t?p=0:e.lineIndentt)&&(P(e,t,A,!0,r)&&(m?d=e.result:h=e.result),m||(U(e,l,p,f,d,h,o,a),f=d=h=null),Y(e,!0,-1),s=e.input.charCodeAt(e.position)),e.lineIndent>t&&0!==s)N(e,"bad indentation of a mapping entry");else if(e.lineIndentc&&(c=e.lineIndent),S(p))u++;else{if(e.lineIndent=t){a=!0,f=e.input.charCodeAt(e.position);continue}e.position=o,e.line=s,e.lineStart=c,e.lineIndent=u;break}}a&&(L(e,r,o,!1),B(e,e.line-s),r=o=e.position,a=!1),I(f)||(o=e.position+1),f=e.input.charCodeAt(++e.position)}if(L(e,r,o,!1),e.result)return 1;e.kind=l,e.result=p}}(e,i,g===n)&&(d=!0,null===e.tag&&(e.tag="?")):(d=!0,null===e.tag&&null===e.anchor||N(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===p&&(d=s&&K(e,r))),null!==e.tag&&"!"!==e.tag)if("?"===e.tag){for(null!==e.result&&"scalar"!==e.kind&&N(e,'unacceptable node kind for ! tag; it should be "scalar", not "'+e.kind+'"'),c=0,u=e.implicitTypes.length;c tag; it should be "'+l.kind+'", not "'+e.kind+'"'),l.resolve(e.result)?(e.result=l.construct(e.result),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):N(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):N(e,"unknown tag !<"+e.tag+">");return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||d}function $(e,t){t=t||{},0!==(e=String(e)).length&&(10!==e.charCodeAt(e.length-1)&&13!==e.charCodeAt(e.length-1)&&(e+="\n"),65279===e.charCodeAt(0)&&(e=e.slice(1)));var n=new F(e,t),e=e.indexOf("\0");for(-1!==e&&(n.position=e,N(n,"null byte is not allowed in input")),n.input+="\0";32===n.input.charCodeAt(n.position);)n.lineIndent+=1,n.position+=1;for(;n.positiont/2-1){n=" ... ",i+=5;break}for(r="",o=this.position;ot/2-1){r=" ... ",o-=5;break}return a=this.buffer.slice(i,o),s.repeat(" ",e)+n+a+r+"\n"+s.repeat(" ",e+this.position-i+n.length)+"^"},i.prototype.toString=function(e){var t="";return this.name&&(t+='in "'+this.name+'" '),t+="at line "+(this.line+1)+", column "+(this.column+1),e||(e=this.getSnippet())&&(t+=":\n"+e),t},t.exports=i},{"./common":2}],7:[function(e,t,n){"use strict";var r=e("./common"),o=e("./exception"),a=e("./type");function s(e,t,i){var r=[];return e.include.forEach(function(e){i=s(e,t,i)}),e[t].forEach(function(n){i.forEach(function(e,t){e.tag===n.tag&&e.kind===n.kind&&r.push(t)}),i.push(n)}),i.filter(function(e,t){return-1===r.indexOf(t)})}function c(e){this.include=e.include||[],this.implicit=e.implicit||[],this.explicit=e.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&"scalar"!==e.loadKind)throw new o("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=s(this,"implicit",[]),this.compiledExplicit=s(this,"explicit",[]),this.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{}};function i(e){n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e>16&255),o.push(r>>8&255),o.push(255&r)),r=r<<6|i.indexOf(t.charAt(a));return 0==(e=n%4*6)?(o.push(r>>16&255),o.push(r>>8&255),o.push(255&r)):18==e?(o.push(r>>10&255),o.push(r>>2&255)):12==e&&o.push(r>>4&255),s?s.from?s.from(o):new s(o):o},predicate:function(e){return s&&s.isBuffer(e)},represent:function(e){for(var t,n="",i=0,r=e.length,o=c,a=0;a>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[63&i]),i=(i<<8)+e[a];return 0==(t=r%3)?(n+=o[i>>18&63],n+=o[i>>12&63],n+=o[i>>6&63],n+=o[63&i]):2==t?(n+=o[i>>10&63],n+=o[i>>4&63],n+=o[i<<2&63],n+=o[64]):1==t&&(n+=o[i>>2&63],n+=o[i<<4&63],n+=o[64],n+=o[64]),n}})},{"../type":13}],15:[function(e,t,n){"use strict";e=e("../type");t.exports=new e("tag:yaml.org,2002:bool",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t=e.length;return 4===t&&("true"===e||"True"===e||"TRUE"===e)||5===t&&("false"===e||"False"===e||"FALSE"===e)},construct:function(e){return"true"===e||"True"===e||"TRUE"===e},predicate:function(e){return"[object Boolean]"===Object.prototype.toString.call(e)},represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})},{"../type":13}],16:[function(e,t,n){"use strict";var i=e("../common"),e=e("../type"),r=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var o=/^[-+]?[0-9]+e/;t.exports=new e("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!r.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n=e.replace(/_/g,"").toLowerCase(),e="-"===n[0]?-1:1,i=[];return 0<="+-".indexOf(n[0])&&(n=n.slice(1)),".inf"===n?1==e?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===n?NaN:0<=n.indexOf(":")?(n.split(":").forEach(function(e){i.unshift(parseFloat(e,10))}),n=0,t=1,i.forEach(function(e){n+=e*t,t*=60}),e*n):e*parseFloat(n,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||i.isNegativeZero(e))},represent:function(e,t){if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(i.isNegativeZero(e))return"-0.0";return e=e.toString(10),o.test(e)?e.replace("e",".e"):e},defaultStyle:"lowercase"})},{"../common":2,"../type":13}],17:[function(e,t,n){"use strict";var i=e("../common"),e=e("../type");t.exports=new e("tag:yaml.org,2002:int",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i,r,o=e.length,a=0,s=!1;if(!o)return!1;if("-"!==(t=e[a])&&"+"!==t||(t=e[++a]),"0"===t){if(a+1===o)return!0;if("b"===(t=e[++a])){for(a++;a */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + +function State(options) { + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// [24] b-line-feed ::= #xA /* LF */ +// [25] b-carriage-return ::= #xD /* CR */ +// [3] c-byte-order-mark ::= #xFEFF +function isNsChar(c) { + return isPrintable(c) && !isWhitespace(c) + // byte-order-mark + && c !== 0xFEFF + // b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe(c, prev) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // - ":" - "#" + // /* An ns-char preceding */ "#" + && c !== CHAR_COLON + && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable(c) && c !== 0xFEFF + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { + var i; + var char, prev_char; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(string.charCodeAt(0)) + && !isWhitespace(string.charCodeAt(string.length - 1)); + + if (singleLineOnly) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + return plain && !testAmbiguousType(string) + ? STYLE_PLAIN : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { + return "'" + string + "'"; + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; + + for (var i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). + if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { + nextChar = string.charCodeAt(i + 1); + if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { + // Combine the surrogate pair and store it escaped. + result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; + } + } + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; + + for (index = 0, length = object.length; index < length; index += 1) { + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (index !== 0) pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + state.tag = explicit ? type.tag : '?'; + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; + if (block && (state.dump.length !== 0)) { + writeBlockSequence(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey); + } + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; + + return ''; +} + +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + +module.exports.dump = dump; +module.exports.safeDump = safeDump; diff --git a/node_modules/js-yaml/lib/js-yaml/exception.js b/node_modules/js-yaml/lib/js-yaml/exception.js new file mode 100644 index 0000000..b744a1e --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/exception.js @@ -0,0 +1,43 @@ +// YAML error class. http://stackoverflow.com/questions/8458984 +// +'use strict'; + +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; + + +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; + + result += this.reason || '(unknown reason)'; + + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } + + return result; +}; + + +module.exports = YAMLException; diff --git a/node_modules/js-yaml/lib/js-yaml/loader.js b/node_modules/js-yaml/lib/js-yaml/loader.js new file mode 100644 index 0000000..d7484a5 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/loader.js @@ -0,0 +1,1644 @@ +'use strict'; + +/*eslint-disable max-len,no-use-before-define*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Mark = require('./mark'); +var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); +var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); + + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = {}, + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _pos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + _pos = state.position; + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else { + break; // Reading is done. Go to the epilogue. + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag !== null && state.tag !== '!') { + if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} + + +function safeLoadAll(input, iterator, options) { + if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} + + +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; diff --git a/node_modules/js-yaml/lib/js-yaml/mark.js b/node_modules/js-yaml/lib/js-yaml/mark.js new file mode 100644 index 0000000..47b265c --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/mark.js @@ -0,0 +1,76 @@ +'use strict'; + + +var common = require('./common'); + + +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} + + +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; + + if (!this.buffer) return null; + + indent = indent || 4; + maxLength = maxLength || 75; + + head = ''; + start = this.position; + + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } + } + + tail = ''; + end = this.position; + + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } + } + + snippet = this.buffer.slice(start, end); + + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; +}; + + +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; + + if (this.name) { + where += 'in "' + this.name + '" '; + } + + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); + + if (!compact) { + snippet = this.getSnippet(); + + if (snippet) { + where += ':\n' + snippet; + } + } + + return where; +}; + + +module.exports = Mark; diff --git a/node_modules/js-yaml/lib/js-yaml/schema.js b/node_modules/js-yaml/lib/js-yaml/schema.js new file mode 100644 index 0000000..ca7cf47 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema.js @@ -0,0 +1,108 @@ +'use strict'; + +/*eslint-disable max-len*/ + +var common = require('./common'); +var YAMLException = require('./exception'); +var Type = require('./type'); + + +function compileList(schema, name, result) { + var exclude = []; + + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); + + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); + } + }); + + result.push(currentType); + }); + + return result.filter(function (type, index) { + return exclude.indexOf(index) === -1; + }); +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; + + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; + + this.implicit.forEach(function (type) { + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); + + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} + + +Schema.DEFAULT = null; + + +Schema.create = function createSchema() { + var schemas, types; + + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; + + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; + + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); + } + + schemas = common.toArray(schemas); + types = common.toArray(types); + + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); + } + + if (!types.every(function (type) { return type instanceof Type; })) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + return new Schema({ + include: schemas, + explicit: types + }); +}; + + +module.exports = Schema; diff --git a/node_modules/js-yaml/lib/js-yaml/schema/core.js b/node_modules/js-yaml/lib/js-yaml/schema/core.js new file mode 100644 index 0000000..206daab --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema/core.js @@ -0,0 +1,18 @@ +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./json') + ] +}); diff --git a/node_modules/js-yaml/lib/js-yaml/schema/default_full.js b/node_modules/js-yaml/lib/js-yaml/schema/default_full.js new file mode 100644 index 0000000..a55ef42 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema/default_full.js @@ -0,0 +1,25 @@ +// JS-YAML's default schema for `load` function. +// It is not described in the YAML specification. +// +// This schema is based on JS-YAML's default safe schema and includes +// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. +// +// Also this schema is used as default base schema at `Schema.create` function. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = Schema.DEFAULT = new Schema({ + include: [ + require('./default_safe') + ], + explicit: [ + require('../type/js/undefined'), + require('../type/js/regexp'), + require('../type/js/function') + ] +}); diff --git a/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js b/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js new file mode 100644 index 0000000..11d89bb --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js @@ -0,0 +1,28 @@ +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./core') + ], + implicit: [ + require('../type/timestamp'), + require('../type/merge') + ], + explicit: [ + require('../type/binary'), + require('../type/omap'), + require('../type/pairs'), + require('../type/set') + ] +}); diff --git a/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js b/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js new file mode 100644 index 0000000..b7a33eb --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js @@ -0,0 +1,17 @@ +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + explicit: [ + require('../type/str'), + require('../type/seq'), + require('../type/map') + ] +}); diff --git a/node_modules/js-yaml/lib/js-yaml/schema/json.js b/node_modules/js-yaml/lib/js-yaml/schema/json.js new file mode 100644 index 0000000..5be3dbf --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/schema/json.js @@ -0,0 +1,25 @@ +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + +'use strict'; + + +var Schema = require('../schema'); + + +module.exports = new Schema({ + include: [ + require('./failsafe') + ], + implicit: [ + require('../type/null'), + require('../type/bool'), + require('../type/int'), + require('../type/float') + ] +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type.js b/node_modules/js-yaml/lib/js-yaml/type.js new file mode 100644 index 0000000..90b702a --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type.js @@ -0,0 +1,61 @@ +'use strict'; + +var YAMLException = require('./exception'); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; diff --git a/node_modules/js-yaml/lib/js-yaml/type/binary.js b/node_modules/js-yaml/lib/js-yaml/type/binary.js new file mode 100644 index 0000000..10b1875 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/binary.js @@ -0,0 +1,138 @@ +'use strict'; + +/*eslint-disable no-bitwise*/ + +var NodeBuffer; + +try { + // A trick for browserified version, to not include `Buffer` shim + var _require = require; + NodeBuffer = _require('buffer').Buffer; +} catch (__) {} + +var Type = require('../type'); + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + // Support node 6.+ Buffer API when available + return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); + } + + return result; +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/bool.js b/node_modules/js-yaml/lib/js-yaml/type/bool.js new file mode 100644 index 0000000..cb77459 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/bool.js @@ -0,0 +1,35 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/float.js b/node_modules/js-yaml/lib/js-yaml/type/float.js new file mode 100644 index 0000000..127671b --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/float.js @@ -0,0 +1,116 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign, base, digits; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); + + value = 0.0; + base = 1; + + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); + + return sign * value; + + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/int.js b/node_modules/js-yaml/lib/js-yaml/type/int.js new file mode 100644 index 0000000..ba61c5f --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/int.js @@ -0,0 +1,173 @@ +'use strict'; + +var common = require('../common'); +var Type = require('../type'); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + // base 10 (except 0) or base 60 + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch === ':') break; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + // if !base60 - done; + if (ch !== ':') return true; + + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value, 16); + return sign * parseInt(value, 8); + } + + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); + + value = 0; + base = 1; + + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); + + return sign * value; + + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/js/function.js b/node_modules/js-yaml/lib/js-yaml/type/js/function.js new file mode 100644 index 0000000..8fab8c4 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/js/function.js @@ -0,0 +1,93 @@ +'use strict'; + +var esprima; + +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + // workaround to exclude package from browserify list. + var _require = require; + esprima = _require('esprima'); +} catch (_) { + /* eslint-disable no-redeclare */ + /* global window */ + if (typeof window !== 'undefined') esprima = window.esprima; +} + +var Type = require('../../type'); + +function resolveJavascriptFunction(data) { + if (data === null) return false; + + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + return false; + } + + return true; + } catch (err) { + return false; + } +} + +function constructJavascriptFunction(data) { + /*jslint evil:true*/ + + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; + + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + throw new Error('Failed to resolve function'); + } + + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); + + body = ast.body[0].expression.body.range; + + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + if (ast.body[0].expression.body.type === 'BlockStatement') { + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); + } + // ES6 arrow functions can omit the BlockStatement. In that case, just return + // the body. + /*eslint-disable no-new-func*/ + return new Function(params, 'return ' + source.slice(body[0], body[1])); +} + +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} + +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js b/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js new file mode 100644 index 0000000..43fa470 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js @@ -0,0 +1,60 @@ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; + + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + + if (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; + } + + return true; +} + +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // `/foo/gim` - tail can be maximum 4 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); + } + + return new RegExp(regexp, modifiers); +} + +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; + + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; + + return result; +} + +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; +} + +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js b/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js new file mode 100644 index 0000000..95b5569 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js @@ -0,0 +1,28 @@ +'use strict'; + +var Type = require('../../type'); + +function resolveJavascriptUndefined() { + return true; +} + +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} + +function representJavascriptUndefined() { + return ''; +} + +function isUndefined(object) { + return typeof object === 'undefined'; +} + +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/map.js b/node_modules/js-yaml/lib/js-yaml/type/map.js new file mode 100644 index 0000000..f327bee --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/map.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/merge.js b/node_modules/js-yaml/lib/js-yaml/type/merge.js new file mode 100644 index 0000000..ae08a86 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/merge.js @@ -0,0 +1,12 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/null.js b/node_modules/js-yaml/lib/js-yaml/type/null.js new file mode 100644 index 0000000..6874daa --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/null.js @@ -0,0 +1,34 @@ +'use strict'; + +var Type = require('../type'); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/omap.js b/node_modules/js-yaml/lib/js-yaml/type/omap.js new file mode 100644 index 0000000..b2b5323 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/omap.js @@ -0,0 +1,44 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/pairs.js b/node_modules/js-yaml/lib/js-yaml/type/pairs.js new file mode 100644 index 0000000..74b5240 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/pairs.js @@ -0,0 +1,53 @@ +'use strict'; + +var Type = require('../type'); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/seq.js b/node_modules/js-yaml/lib/js-yaml/type/seq.js new file mode 100644 index 0000000..be8f77f --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/seq.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/set.js b/node_modules/js-yaml/lib/js-yaml/type/set.js new file mode 100644 index 0000000..f885a32 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/set.js @@ -0,0 +1,29 @@ +'use strict'; + +var Type = require('../type'); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/str.js b/node_modules/js-yaml/lib/js-yaml/type/str.js new file mode 100644 index 0000000..27acc10 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/str.js @@ -0,0 +1,8 @@ +'use strict'; + +var Type = require('../type'); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); diff --git a/node_modules/js-yaml/lib/js-yaml/type/timestamp.js b/node_modules/js-yaml/lib/js-yaml/type/timestamp.js new file mode 100644 index 0000000..8fa9c58 --- /dev/null +++ b/node_modules/js-yaml/lib/js-yaml/type/timestamp.js @@ -0,0 +1,88 @@ +'use strict'; + +var Type = require('../type'); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); diff --git a/node_modules/js-yaml/package.json b/node_modules/js-yaml/package.json new file mode 100644 index 0000000..0d23667 --- /dev/null +++ b/node_modules/js-yaml/package.json @@ -0,0 +1,49 @@ +{ + "name": "js-yaml", + "version": "3.14.1", + "description": "YAML 1.2 parser and serializer", + "keywords": [ + "yaml", + "parser", + "serializer", + "pyyaml" + ], + "homepage": "https://github.com/nodeca/js-yaml", + "author": "Vladimir Zapparov ", + "contributors": [ + "Aleksey V Zapparov (http://www.ixti.net/)", + "Vitaly Puzrin (https://github.com/puzrin)", + "Martin Grenfell (http://got-ravings.blogspot.com)" + ], + "license": "MIT", + "repository": "nodeca/js-yaml", + "files": [ + "index.js", + "lib/", + "bin/", + "dist/" + ], + "bin": { + "js-yaml": "bin/js-yaml.js" + }, + "unpkg": "dist/js-yaml.min.js", + "jsdelivr": "dist/js-yaml.min.js", + "dependencies": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + }, + "devDependencies": { + "ansi": "^0.3.1", + "benchmark": "^2.1.4", + "browserify": "^16.2.2", + "codemirror": "^5.13.4", + "eslint": "^7.0.0", + "fast-check": "^1.24.2", + "istanbul": "^0.4.5", + "mocha": "^7.1.2", + "uglify-js": "^3.0.1" + }, + "scripts": { + "test": "make test" + } +} diff --git a/node_modules/jsesc/LICENSE-MIT.txt b/node_modules/jsesc/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/jsesc/LICENSE-MIT.txt @@ -0,0 +1,20 @@ +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. diff --git a/node_modules/jsesc/README.md b/node_modules/jsesc/README.md new file mode 100644 index 0000000..aae2b13 --- /dev/null +++ b/node_modules/jsesc/README.md @@ -0,0 +1,421 @@ +# jsesc [![Build status](https://travis-ci.org/mathiasbynens/jsesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/jsesc) [![Code coverage status](https://coveralls.io/repos/mathiasbynens/jsesc/badge.svg)](https://coveralls.io/r/mathiasbynens/jsesc) [![Dependency status](https://gemnasium.com/mathiasbynens/jsesc.svg)](https://gemnasium.com/mathiasbynens/jsesc) + +Given some data, _jsesc_ returns a stringified representation of that data. jsesc is similar to `JSON.stringify()` except: + +1. it outputs JavaScript instead of JSON [by default](#json), enabling support for data structures like ES6 maps and sets; +2. it offers [many options](#api) to customize the output; +3. its output is ASCII-safe [by default](#minimal), thanks to its use of [escape sequences](https://mathiasbynens.be/notes/javascript-escapes) where needed. + +For any input, jsesc generates the shortest possible valid printable-ASCII-only output. [Here’s an online demo.](https://mothereff.in/js-escapes) + +jsesc’s output can be used instead of `JSON.stringify`’s to avoid [mojibake](https://en.wikipedia.org/wiki/Mojibake) and other encoding issues, or even to [avoid errors](https://twitter.com/annevk/status/380000829643571200) when passing JSON-formatted data (which may contain U+2028 LINE SEPARATOR, U+2029 PARAGRAPH SEPARATOR, or [lone surrogates](https://esdiscuss.org/topic/code-points-vs-unicode-scalar-values#content-14)) to a JavaScript parser or an UTF-8 encoder. + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install jsesc +``` + +In [Node.js](https://nodejs.org/): + +```js +const jsesc = require('jsesc'); +``` + +## API + +### `jsesc(value, options)` + +This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in JavaScript strings](https://mathiasbynens.be/notes/javascript-escapes). The first supported value type is strings: + +```js +jsesc('Ich ♥ Bücher'); +// → 'Ich \\u2665 B\\xFCcher' + +jsesc('foo 𝌆 bar'); +// → 'foo \\uD834\\uDF06 bar' +``` + +Instead of a string, the `value` can also be an array, an object, a map, a set, or a buffer. In such cases, `jsesc` returns a stringified version of the value where any characters that are not printable ASCII symbols are escaped in the same way. + +```js +// Escaping an array +jsesc([ + 'Ich ♥ Bücher', 'foo 𝌆 bar' +]); +// → '[\'Ich \\u2665 B\\xFCcher\',\'foo \\uD834\\uDF06 bar\']' + +// Escaping an object +jsesc({ + 'Ich ♥ Bücher': 'foo 𝌆 bar' +}); +// → '{\'Ich \\u2665 B\\xFCcher\':\'foo \\uD834\\uDF06 bar\'}' +``` + +The optional `options` argument accepts an object with the following options: + +#### `quotes` + +The default value for the `quotes` option is `'single'`. This means that any occurrences of `'` in the input string are escaped as `\'`, so that the output can be used in a string literal wrapped in single quotes. + +```js +jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.'); +// → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' + +jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'single' +}); +// → '`Lorem` ipsum "dolor" sit \\\'amet\\\' etc.' +// → "`Lorem` ipsum \"dolor\" sit \\'amet\\' etc." +``` + +If you want to use the output as part of a string literal wrapped in double quotes, set the `quotes` option to `'double'`. + +```js +jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'double' +}); +// → '`Lorem` ipsum \\"dolor\\" sit \'amet\' etc.' +// → "`Lorem` ipsum \\\"dolor\\\" sit 'amet' etc." +``` + +If you want to use the output as part of a template literal (i.e. wrapped in backticks), set the `quotes` option to `'backtick'`. + +```js +jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'backtick' +}); +// → '\\`Lorem\\` ipsum "dolor" sit \'amet\' etc.' +// → "\\`Lorem\\` ipsum \"dolor\" sit 'amet' etc." +// → `\\\`Lorem\\\` ipsum "dolor" sit 'amet' etc.` +``` + +This setting also affects the output for arrays and objects: + +```js +jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { + 'quotes': 'double' +}); +// → '{"Ich \\u2665 B\\xFCcher":"foo \\uD834\\uDF06 bar"}' + +jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], { + 'quotes': 'double' +}); +// → '["Ich \\u2665 B\\xFCcher","foo \\uD834\\uDF06 bar"]' +``` + +#### `numbers` + +The default value for the `numbers` option is `'decimal'`. This means that any numeric values are represented using decimal integer literals. Other valid options are `binary`, `octal`, and `hexadecimal`, which result in binary integer literals, octal integer literals, and hexadecimal integer literals, respectively. + +```js +jsesc(42, { + 'numbers': 'binary' +}); +// → '0b101010' + +jsesc(42, { + 'numbers': 'octal' +}); +// → '0o52' + +jsesc(42, { + 'numbers': 'decimal' +}); +// → '42' + +jsesc(42, { + 'numbers': 'hexadecimal' +}); +// → '0x2A' +``` + +#### `wrap` + +The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is a valid JavaScript string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting. + +```js +jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'single', + 'wrap': true +}); +// → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\'' +// → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'" + +jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { + 'quotes': 'double', + 'wrap': true +}); +// → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."' +// → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\"" +``` + +#### `es6` + +The `es6` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any astral Unicode symbols in the input are escaped using [ECMAScript 6 Unicode code point escape sequences](https://mathiasbynens.be/notes/javascript-escapes#unicode-code-point) instead of using separate escape sequences for each surrogate half. If backwards compatibility with ES5 environments is a concern, don’t enable this setting. If the `json` setting is enabled, the value for the `es6` setting is ignored (as if it was `false`). + +```js +// By default, the `es6` option is disabled: +jsesc('foo 𝌆 bar 💩 baz'); +// → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz' + +// To explicitly disable it: +jsesc('foo 𝌆 bar 💩 baz', { + 'es6': false +}); +// → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz' + +// To enable it: +jsesc('foo 𝌆 bar 💩 baz', { + 'es6': true +}); +// → 'foo \\u{1D306} bar \\u{1F4A9} baz' +``` + +#### `escapeEverything` + +The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output are escaped — even printable ASCII symbols. + +```js +jsesc('lolwat"foo\'bar', { + 'escapeEverything': true +}); +// → '\\x6C\\x6F\\x6C\\x77\\x61\\x74\\"\\x66\\x6F\\x6F\\\'\\x62\\x61\\x72' +// → "\\x6C\\x6F\\x6C\\x77\\x61\\x74\\\"\\x66\\x6F\\x6F\\'\\x62\\x61\\x72" +``` + +This setting also affects the output for string literals within arrays and objects. + +#### `minimal` + +The `minimal` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, only a limited set of symbols in the output are escaped: + +* U+0000 `\0` +* U+0008 `\b` +* U+0009 `\t` +* U+000A `\n` +* U+000C `\f` +* U+000D `\r` +* U+005C `\\` +* U+2028 `\u2028` +* U+2029 `\u2029` +* whatever symbol is being used for wrapping string literals (based on [the `quotes` option](#quotes)) + +Note: with this option enabled, jsesc output is no longer guaranteed to be ASCII-safe. + +```js +jsesc('foo\u2029bar\nbaz©qux𝌆flops', { + 'minimal': false +}); +// → 'foo\\u2029bar\\nbaz©qux𝌆flops' +``` + +#### `isScriptContext` + +The `isScriptContext` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, occurrences of [`` or `